iobroker.javascript 9.3.0 → 10.0.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 (220) hide show
  1. package/README.md +8 -9
  2. package/admin/assets/AiChatPanel-p0KAg6Cs.js +237 -0
  3. package/admin/assets/AiDatapointProvider-DzFpUKkT.js +2 -0
  4. package/admin/assets/AiDiffView-BPTLnNx1.js +1 -0
  5. package/admin/assets/AiInlineProvider-CaHd2G2Q.js +5 -0
  6. package/admin/assets/AiScriptAnalyzer--BHML2rN.js +9 -0
  7. package/admin/assets/BlocklyEditor-CAjVMhYT.js +81 -0
  8. package/admin/assets/ContextWrapper-BVc8wTK_.css +1 -0
  9. package/admin/assets/ContextWrapper-D9CrnNKs.js +127 -0
  10. package/admin/assets/Debugger-SjROokFI.js +15 -0
  11. package/admin/assets/Error-DDfrxAt2.js +1 -0
  12. package/admin/assets/Import-DpTg1Jow.js +1 -0
  13. package/admin/assets/RulesEditor-BSRFWpEm.css +1 -0
  14. package/admin/assets/RulesEditor-D0hgrcBc.js +1 -0
  15. package/admin/assets/ScriptEditor-BGIuoNei.js +2 -0
  16. package/admin/assets/ScriptEditorVanillaMonaco-DyMQtoTQ.js +3 -0
  17. package/admin/assets/_virtual_mf-localSharedImportMap___mfe_internal__iobroker_javascript__mf_owner__1-DWJotR1B.js +1 -0
  18. package/admin/assets/_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-CxICLr5Z.js +1243 -0
  19. package/admin/assets/_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-BBAXJaqI.js +9 -0
  20. package/admin/assets/aiCodeLensProvider-hyAmut0e.js +4 -0
  21. package/admin/assets/aiPromptBuilder-Bs27qOHT.js +7 -0
  22. package/admin/assets/applyCodeEdit-D3nb7erO.js +1 -0
  23. package/admin/assets/blocklyDarkTheme-DEiAX5DT.js +1 -0
  24. package/admin/assets/cronHoverProvider-pKJkSevo.js +2 -0
  25. package/admin/assets/dist-uw5orDgd.js +4 -0
  26. package/admin/assets/{docs-compact-CKNGiYh2.js → docs-compact-D7rpMc7r.js} +2 -2
  27. package/admin/assets/hostInit-BFg5u9hY.js +1 -0
  28. package/admin/assets/index-B1gICjdq.js +192 -0
  29. package/admin/assets/index-BHhhebRG.css +1 -0
  30. package/admin/assets/inlineChatWidget-ZaisTOLh.js +2 -0
  31. package/admin/assets/inlineDiffController-hTwHHqcc.js +16 -0
  32. package/admin/assets/mf-entry-bootstrap-0-d6052b31.js +36 -0
  33. package/admin/assets/mjs-DWqivHEk.js +90 -0
  34. package/admin/assets/rolldown-runtime-C0FnF6B9.js +1 -0
  35. package/admin/assets/stateHoverProvider-C7DawIs-.js +9 -0
  36. package/admin/assets/virtualExposes-Ed0lGq7k.js +1 -0
  37. package/admin/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__iobroker_javascript__remoteEntry_js-BYs71IQF.js +1 -0
  38. package/admin/assets/virtual_mf-exposes___mfe_internal__iobroker_javascript__remoteEntry_js-DnnXQRkG.js +1 -0
  39. package/admin/assets/vite-preload-helper-B7qeedMF.js +1 -0
  40. package/admin/custom/assets/Components-BrDyDHXh.js +1 -0
  41. package/admin/custom/assets/Components-DftM8alF.css +1 -0
  42. package/admin/custom/assets/_virtual_mf-localSharedImportMap___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1-CyYJM2-v.js +1 -0
  43. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_emotion_mf_1_react__loadShare__.js-BdzCssLn.js +1 -0
  44. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_emotion_mf_1_styled__loadShare__.js-CGb5Cofy.js +1 -0
  45. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BVCIAgbo.js +1243 -0
  46. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare___mf_0_iobroker_mf_1_json_mf_2_config__loadShare__.js-BkB0anQX.js +1494 -0
  47. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare__leaflet__loadShare__.js-h-rCw3iz.js +1 -0
  48. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-BotqDuw-.js +9 -0
  49. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__prebuild__date_mf_2_fns__prebuild__-Cb5TR7FB.js +1 -0
  50. package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomJavascriptSet__mf_owner__1__prebuild__leaflet__prebuild__-DARUoA03.js +1 -0
  51. package/admin/custom/assets/hostInit-DJx2uXXy.js +1 -0
  52. package/admin/custom/assets/index-uEKAoVT7.js +1 -0
  53. package/admin/custom/assets/lib-Yj8cfN0A.js +3 -0
  54. package/admin/custom/assets/mf-entry-bootstrap-0-77793feb.js +36 -0
  55. package/admin/custom/assets/rolldown-runtime-BcKkbAw3.js +1 -0
  56. package/admin/custom/assets/setYear-DJ9FbdkO.js +1 -0
  57. package/admin/custom/assets/virtualExposes-CxDjLoYu.js +1 -0
  58. package/admin/custom/assets/virtual_mf-REMOTE_ENTRY_ID___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-BU-ugy_7.js +1 -0
  59. package/admin/custom/assets/virtual_mf-exposes-ssr___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-BEfZbrf7.js +2 -0
  60. package/admin/custom/assets/virtual_mf-exposes___mfe_internal__ConfigCustomJavascriptSet__customComponents_js-CTeZ0Jpm.js +2 -0
  61. package/admin/custom/assets/vite-preload-helper-B7qeedMF.js +1 -0
  62. package/admin/custom/customComponents.js +1 -1
  63. package/admin/jsonConfig.json +1 -1
  64. package/admin/mf-manifest.json +1 -1
  65. package/admin/mf-stats.json +1 -0
  66. package/admin/remoteEntry.js +1 -1
  67. package/admin/tab.html +12 -17
  68. package/build/lib/debugger.js +1 -1
  69. package/build/lib/debugger.js.map +1 -1
  70. package/build/lib/eventObj.js.map +1 -1
  71. package/build/lib/inspect.js.map +1 -1
  72. package/build/lib/javascript.d.ts +18 -19
  73. package/build/lib/nodeModulesManagement.js +3 -1
  74. package/build/lib/nodeModulesManagement.js.map +1 -1
  75. package/build/lib/protectFs.js.map +1 -1
  76. package/build/lib/sandbox.js +104 -43
  77. package/build/lib/sandbox.js.map +1 -1
  78. package/build/lib/scheduler.js.map +1 -1
  79. package/build/lib/tools.js +1 -1
  80. package/build/lib/tools.js.map +1 -1
  81. package/build/lib/typescriptSettings.js +16 -10
  82. package/build/lib/typescriptSettings.js.map +1 -1
  83. package/build/lib/typescriptTools.js +2 -2
  84. package/build/lib/typescriptTools.js.map +1 -1
  85. package/build/main.js +41 -29
  86. package/build/main.js.map +1 -1
  87. package/build/src/lib/aiProviderResolver.js +107 -0
  88. package/build/src/lib/aiProviderResolver.js.map +1 -0
  89. package/build/src/lib/anthropicAdapter.js +175 -0
  90. package/build/src/lib/anthropicAdapter.js.map +1 -0
  91. package/build/src/lib/consts.js +346 -0
  92. package/build/src/lib/consts.js.map +1 -0
  93. package/build/src/lib/convert.js +121 -0
  94. package/build/src/lib/convert.js.map +1 -0
  95. package/build/src/lib/crypto.js +32 -0
  96. package/build/src/lib/crypto.js.map +1 -0
  97. package/build/src/lib/debug.js +163 -0
  98. package/build/src/lib/debug.js.map +1 -0
  99. package/build/src/lib/debugger.js +1135 -0
  100. package/build/src/lib/debugger.js.map +1 -0
  101. package/build/src/lib/eventObj.js +194 -0
  102. package/build/src/lib/eventObj.js.map +1 -0
  103. package/build/src/lib/inspect.js +728 -0
  104. package/build/src/lib/inspect.js.map +1 -0
  105. package/build/src/lib/mirror.js +634 -0
  106. package/build/src/lib/mirror.js.map +1 -0
  107. package/build/src/lib/nodeModulesManagement.js +26 -0
  108. package/build/src/lib/nodeModulesManagement.js.map +1 -0
  109. package/build/src/lib/patternCompareFunctions.js +293 -0
  110. package/build/src/lib/patternCompareFunctions.js.map +1 -0
  111. package/build/src/lib/protectFs.js +554 -0
  112. package/build/src/lib/protectFs.js.map +1 -0
  113. package/build/src/lib/sandbox.js +4897 -0
  114. package/build/src/lib/sandbox.js.map +1 -0
  115. package/build/src/lib/scheduler.js +555 -0
  116. package/build/src/lib/scheduler.js.map +1 -0
  117. package/build/src/lib/tools.js +188 -0
  118. package/build/src/lib/tools.js.map +1 -0
  119. package/build/src/lib/typescriptSettings.js +39 -0
  120. package/build/src/lib/typescriptSettings.js.map +1 -0
  121. package/build/src/lib/typescriptTools.js +435 -0
  122. package/build/src/lib/typescriptTools.js.map +1 -0
  123. package/build/src/lib/utils.js +66 -0
  124. package/build/src/lib/utils.js.map +1 -0
  125. package/build/src/lib/words.js +76 -0
  126. package/build/src/lib/words.js.map +1 -0
  127. package/build/src/main.js +3414 -0
  128. package/build/src/main.js.map +1 -0
  129. package/build/types.d.ts +6 -14
  130. package/io-package.json +28 -28
  131. package/package.json +16 -17
  132. package/admin/assets/AiChatPanel-BvND3KNP.js +0 -317
  133. package/admin/assets/AiDatapointProvider-B0i3I5Fm.js +0 -2
  134. package/admin/assets/AiDiffView-RPozjjHf.js +0 -1
  135. package/admin/assets/AiInlineProvider-DkgjVSFQ.js +0 -7
  136. package/admin/assets/Save-CkuNSiWL.js +0 -1
  137. package/admin/assets/ScriptEditor-1BwI9a_X.js +0 -2
  138. package/admin/assets/ScriptEditorVanillaMonaco-BPK75VNu.js +0 -3
  139. package/admin/assets/applyCodeEdit-BdRnbz2g.js +0 -1
  140. package/admin/assets/createSvgIcon-DYs_tNrE.js +0 -8
  141. package/admin/assets/cronHoverProvider-Bg0Vz-1E.js +0 -2
  142. package/admin/assets/hostInit-LzITLWDa.js +0 -1
  143. package/admin/assets/index-45IwpC7_.js +0 -1
  144. package/admin/assets/index-BCK6q-N6.css +0 -1
  145. package/admin/assets/index-BTsjunTt.css +0 -1
  146. package/admin/assets/index-Be9Zg6aF.js +0 -990
  147. package/admin/assets/index-BkyLyaYT.js +0 -8
  148. package/admin/assets/index-CVZSzCXy.js +0 -1
  149. package/admin/assets/index-CxRhXAwi.js +0 -1267
  150. package/admin/assets/index-DUMiVB6k.js +0 -16
  151. package/admin/assets/index-Dsh1HfIY.js +0 -1
  152. package/admin/assets/index-dN73sbyQ.js +0 -193
  153. package/admin/assets/index-fS-54-pB.js +0 -1
  154. package/admin/assets/index-wHNMOf-c.js +0 -5
  155. package/admin/assets/inheritsLoose-CIXm_zPk.js +0 -29
  156. package/admin/assets/inlineChatWidget-Cu6rb4Ar.js +0 -2
  157. package/admin/assets/inlineDiffController-DBLpPOe2.js +0 -16
  158. package/admin/assets/iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js +0 -1
  159. package/admin/assets/iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-CV1_X-Lf.js +0 -1
  160. package/admin/assets/iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js +0 -1
  161. package/admin/assets/iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js +0 -1
  162. package/admin/assets/iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js +0 -1
  163. package/admin/assets/iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js +0 -1
  164. package/admin/assets/iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js +0 -1
  165. package/admin/assets/localSharedImportMap-Cs4ibnCv.js +0 -1
  166. package/admin/assets/preload-helper-BDBacUwf.js +0 -1
  167. package/admin/assets/stateHoverProvider-dvzAyUDH.js +0 -9
  168. package/admin/assets/useTheme-DuTJsNQ-.js +0 -1
  169. package/admin/assets/virtualExposes-BPsCufin.js +0 -1
  170. package/admin/assets/virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-Dus28I2g.js +0 -8
  171. package/admin/custom/assets/Components-BOms95_F.css +0 -1
  172. package/admin/custom/assets/Components-CGiJE5Zh.js +0 -1
  173. package/admin/custom/assets/ConfigCustomJavascriptSet__loadShare___mf_0_emotion_mf_1_react__loadShare__.mjs-sg07E3QA.js +0 -1
  174. package/admin/custom/assets/ConfigCustomJavascriptSet__loadShare___mf_0_emotion_mf_1_styled__loadShare__.mjs-CwjI4A-J.js +0 -1
  175. package/admin/custom/assets/ConfigCustomJavascriptSet__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-B7D2xOvV.js +0 -1
  176. package/admin/custom/assets/ConfigCustomJavascriptSet__loadShare___mf_0_iobroker_mf_1_json_mf_2_config__loadShare__.mjs-ClsgYnEX.js +0 -1
  177. package/admin/custom/assets/ConfigCustomJavascriptSet__loadShare___mf_0_mui_mf_1_icons_mf_2_material__loadShare__.mjs-B551AMx-.js +0 -1
  178. package/admin/custom/assets/ConfigCustomJavascriptSet__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-KsT5vKjV.js +0 -1
  179. package/admin/custom/assets/ConfigCustomJavascriptSet__loadShare___mf_0_mui_mf_1_x_mf_2_date_mf_2_pickers__loadShare__.mjs-DgHZUNxn.js +0 -1
  180. package/admin/custom/assets/ConfigCustomJavascriptSet__loadShare__leaflet__loadShare__.mjs-BYONkEgA.js +0 -1
  181. package/admin/custom/assets/ConfigCustomJavascriptSet__loadShare__react__loadShare__.mjs-BW9Qbxx5.js +0 -1
  182. package/admin/custom/assets/ConfigCustomJavascriptSet__loadShare__react__loadShare__.mjs_commonjs-proxy-2W2BYT2K.js +0 -1
  183. package/admin/custom/assets/ConfigCustomJavascriptSet__loadShare__react_mf_2_dom__loadShare__.mjs-CL--xmjC.js +0 -1
  184. package/admin/custom/assets/ConfigCustomJavascriptSet__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-D8zcZsJo.js +0 -1
  185. package/admin/custom/assets/DefaultPropsProvider-CfKHPa-G.js +0 -1
  186. package/admin/custom/assets/TextField-CxPfV5Sr.js +0 -139
  187. package/admin/custom/assets/ThemeProvider-DSTCckLJ.js +0 -29
  188. package/admin/custom/assets/blue-CagzI6CQ.js +0 -1
  189. package/admin/custom/assets/createSvgIcon-b2B2NI3g.js +0 -1
  190. package/admin/custom/assets/createTheme-MsdB8zt7.js +0 -8
  191. package/admin/custom/assets/defaultTheme-CmVP-QNF.js +0 -1
  192. package/admin/custom/assets/emotion-cache.browser.esm-BgJfNZJN.js +0 -1
  193. package/admin/custom/assets/emotion-react.browser.esm-chZAeh_-.js +0 -1
  194. package/admin/custom/assets/emotion-serialize.esm-BUa21YfQ.js +0 -1
  195. package/admin/custom/assets/emotion-styled.browser.esm-Yi13plpH.js +0 -1
  196. package/admin/custom/assets/emotion-use-insertion-effect-with-fallbacks.browser.esm-CEPeBbh9.js +0 -1
  197. package/admin/custom/assets/extends-CF3RwP-h.js +0 -1
  198. package/admin/custom/assets/hostInit-iUL-wyj1.js +0 -1
  199. package/admin/custom/assets/index-17vbGv00.js +0 -1
  200. package/admin/custom/assets/index-B5DqCD_a.js +0 -1
  201. package/admin/custom/assets/index-BVOepGI5.js +0 -1
  202. package/admin/custom/assets/index-Bvwv5H7k.js +0 -1
  203. package/admin/custom/assets/index-C8_qJ4Y6.js +0 -1523
  204. package/admin/custom/assets/index-CzRngQHl.js +0 -31
  205. package/admin/custom/assets/index-DLNtxshy.js +0 -1
  206. package/admin/custom/assets/index-DSGXVHGh.js +0 -964
  207. package/admin/custom/assets/index-DV76KW3-.js +0 -7
  208. package/admin/custom/assets/index-D_5kZmfw.js +0 -1
  209. package/admin/custom/assets/index-DlQbqHom.js +0 -8
  210. package/admin/custom/assets/index-DpJ18x6R.js +0 -1
  211. package/admin/custom/assets/index-FTmk0JJx.js +0 -55
  212. package/admin/custom/assets/isSameWeek-DDsSIa_t.js +0 -1
  213. package/admin/custom/assets/jsx-runtime-BplTyRFk.js +0 -1
  214. package/admin/custom/assets/leaflet-src-B472P7Y1.js +0 -1
  215. package/admin/custom/assets/localSharedImportMap-C-8wOKN2.js +0 -1
  216. package/admin/custom/assets/preload-helper-BDBacUwf.js +0 -1
  217. package/admin/custom/assets/useTheme-BV4xOYIL.js +0 -1
  218. package/admin/custom/assets/useTheme-ldICnlmf.js +0 -1
  219. package/admin/custom/assets/virtualExposes-D402kVGY.js +0 -2
  220. package/admin/custom/assets/virtual_mf-REMOTE_ENTRY_ID_ConfigCustomJavascriptSet__customComponents_js-CO2hfDx_.js +0 -8
package/README.md CHANGED
@@ -27,9 +27,16 @@ Executes Javascript, Typescript Scripts.
27
27
  -->
28
28
 
29
29
  ## Changelog
30
+ ### 10.0.0 (2026-08-04)
31
+ * (@GermanBluefox) Typescript 6 support
32
+ * (@GermanBluefox) GUI was migrated to React 19 and MUI 9
33
+ * (@GermanBluefox) Showed host name in the instance selection dialog
34
+
35
+ ### 9.3.1 (2026-06-18)
36
+ * (@GermanBluefox) Added the possibility to execute one-way scripts without saving it
37
+
30
38
  ### 9.3.0 (2026-06-17)
31
39
  * (@GermanBluefox) Implemented the support for credentials manager in the configuration
32
- * (@GermanBluefox) Added the possiblilty to execute scripts from AI agent
33
40
 
34
41
  ### 9.2.4 (2026-06-08)
35
42
  * (arteck) Performance optimizations part 2
@@ -41,14 +48,6 @@ Executes Javascript, Typescript Scripts.
41
48
  * (arteck) Performance optimizations done
42
49
  * (@GermanBluefox) Added on mouse over the value of the state
43
50
 
44
- ### 9.2.2 (2026-05-07)
45
- * (Eistee82) Fix: AI chat mode tooltip no longer covers the dropdown options (issue #2201) — moved tooltip to the left of the selector
46
- * (Eistee82) Clarified the AI chat mode descriptions in the tooltip: Agent is for larger models with tool support and handles both analysis and script creation, Code is for smaller models without tool support (uses two-step plan-then-code) — translations updated in all 11 languages
47
- * (@GermanBluefox) Added the "is state exists" block to blockly
48
-
49
- ### 9.2.1 (2026-04-30)
50
- * (@GermanBluefox) See previous changelog entries
51
-
52
51
  ## License
53
52
  The MIT License (MIT)
54
53
 
@@ -0,0 +1,237 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./aiPromptBuilder-Bs27qOHT.js","./rolldown-runtime-C0FnF6B9.js"])))=>i.map(i=>d[i]);
2
+ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{t}from"./vite-preload-helper-B7qeedMF.js";import{Ft as n,Hn as r,It as i,Kt as a,Lt as o,Mn as s,Nt as c,Rt as l,Sn as u,Tn as d,Un as f,_t as p,cn as m,cr as h,f as g,fr as _,gn as v,gt as y,hr as b,ln as x,mn as S,mr as C,or as w,qt as T,st as E,ut as D,vn as O,vt as k,wn as ee,xn as A,yr as j,zt as M}from"./_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-CxICLr5Z.js";import{n as N,r as P,t as F}from"./AiScriptAnalyzer--BHML2rN.js";import{t as I}from"./blocklyDarkTheme-DEiAX5DT.js";import{n as te,r as L}from"./aiPromptBuilder-Bs27qOHT.js";var R=s(r(`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`),z=s(r(`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`),ne=s(r(`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`),B=s(r(`path`,{d:`M9.01 14H2v2h7.01v3L13 15l-3.99-4zm5.98-1v-3H22V8h-7.01V5L11 9z`}),`CompareArrows`),V=s(r(`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`),H=s(r(`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`),re=s(r(`path`,{d:`M2.01 21 23 12 2.01 3 2 10l15 2-15 2z`}),`Send`),U=s(r(`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`);j();var W=e(E(),1),G=t(()=>import(`./docs-compact-D7rpMc7r.js`),[],import.meta.url),K={openai:`img/openai.svg`,anthropic:`img/anthropic.svg`,gemini:`img/gemini.svg`,deepseek:`img/deepseek.svg`,custom:`img/custom.svg`},q={width:16,height:16,flexShrink:0,opacity:.7},ie={ru:`Russian`,en:`English`,de:`German`,es:`Spanish`,fr:`French`,it:`Italian`,pl:`Polish`,nl:`Dutch`,pt:`Portuguese`,uk:`Ukrainian`,"zh-cn":`Chinese`},J=null,Y=null,X=null,Z=null;function ae(){J=null,Y=null,X=null,Z=null}async function Q(e,t){if(J)return J;let n=Object.keys(t)[0];if(!n)return null;let r=await e.sendTo(n,`getAvailableAiProviders`,{}),i=((r==null?void 0:r.providers)||[]).map(e=>e.provider),a=((r==null?void 0:r.providers)||[]).find(e=>e.provider===`custom`);return i.length?(J={providers:i,gptBaseUrl:a==null?void 0:a.baseUrl},J):null}var oe=`embedding.text-embedding.textembedding.embeddinggemma.embed-.-embed.bge-.mxbai-embed.nomic-embed.arctic-embed.snowflake-arctic-embed.all-minilm.multilingual-e5.jina-embed.voyage-.gecko.paraphrase-multilingual.dall-e.gpt-image.image-edit.-image-preview.-image-latest.flash-image.nano-banana.stable-diffusion.sdxl.midjourney.flux-.imagen.sora.veo-.cogvideo.runway-.lumiere.lyria.whisper.tts-.-tts.speech-.audio-preview.mini-tts.mini-transcribe.-transcribe.native-audio.flash-live.gpt-audio.realtime.bark-.xtts.voicebox.moderation.omni-moderation.llama-guard.shieldgemma.prompt-guard.-guardian.safeguard.rerank.reranker.babbage-.davinci-.curie-.text-ada-.text-davinci.text-curie.text-babbage.instructgpt.code-davinci.code-cushman.-turbo-instruct.-search-preview.-search-api.code-search.text-search.similarity-.computer-use-preview.deep-research.robotics.aqa.reader-lm.-nsql.minicheck`.split(`.`);function se(e){let t=e.toLowerCase();return!(oe.some(e=>t.includes(e))||t.startsWith(`claude-1`)||t.startsWith(`claude-instant`))}async function ce(e,t){let n=await Q(e,t);if(!n)return{models:[],providerMap:{},errors:[`No API keys configured`]};let r=Object.keys(t)[0];if(!r)return{models:[],providerMap:{},errors:[g.t(`No running javascript instance found`)]};let i=[],a={},o=[],s=(e,t)=>{for(let n of e)se(n)&&(a[n]||(i.push(n),a[n]=t))},c=[],l=(t,n)=>{c.push(e.sendTo(r,`testApiConnection`,{provider:t===`custom`?`openai`:t}).then(e=>{e.models?s(e.models,t):e.error&&o.push(`${n||t}: ${e.error}`)}).catch(e=>{o.push(`${n||t}: ${String(e)}`)}))},u={openai:`OpenAI`,anthropic:`Anthropic`,gemini:`Gemini`,deepseek:`DeepSeek`,custom:`Custom`};for(let e of n.providers)l(e,u[e]);return await Promise.all(c),i.sort(),{models:i,providerMap:a,errors:o}}async function le(e,t,n){var r;return await e.sendTo(t,`chatCompletion`,{timeout:n.timeout||6e5,model:n.model,provider:n.provider,messages:n.messages,...n.baseUrl?{baseUrl:n.baseUrl}:{},...(r=n.tools)!=null&&r.length?{tools:n.tools}:{}})}async function ue(e){if(Z)return Z;let t=await e.getObjectViewSystem(`state`,``,`香`),n=await e.getObjectViewSystem(`channel`,``,`香`),r=await e.getObjectViewSystem(`device`,``,`香`),i=await e.getObjectViewSystem(`folder`,``,`香`),a=await e.getObjectViewSystem(`enum`,``,`香`);return Z=Object.assign(t,n,r,i,a),Z}async function de(e){return ue(e)}function fe(e,t){return e&&typeof e==`object`?e[t]||e.en:e||``}async function pe(e){if(Y)return Y;let t=g.getLanguage(),n=await ue(e),r=Object.keys(n).sort(),i=new W.default,a=[],o=[`UNREACH_STICKY`],s=[W.Types.info],c=[],l=[],u=[],d=[];r.forEach(e=>{var t,r;((t=n[e])==null?void 0:t.type)===`enum`?c.push(e):(r=n[e])!=null&&(r=r.common)!=null&&r.smartName&&d.push(e)}),c.forEach(e=>{e.startsWith(`enum.rooms.`)?l.push(e):e.startsWith(`enum.functions.`)&&u.push(e);let t=n[e].common.members;t!=null&&t.length&&t.forEach(e=>{n[e]&&!d.includes(e)&&d.push(e)})});let f={id:``,objects:n,_keysOptional:r,_usedIdsOptional:a,ignoreIndicators:o,excludedTypes:s},p=[];d.forEach(e=>{f.id=e;let r=i.detect(f);r&&r.forEach(e=>{var r;let i=(r=e.states.find(e=>e.id))==null?void 0:r.id;if(!i||p.find(e=>e.id===i))return;let a=n[i],o={id:i,name:fe(a.common.name,t),type:a.type,deviceType:e.type,states:e.states.filter(e=>e.id).map(e=>({id:e.id,name:e.name,role:e.defaultRole,type:n[e.id].common.type,unit:n[e.id].common.unit,read:n[e.id].common.read??!0,write:n[e.id].common.write??!0}))},s=i.split(`.`),c,d;(a.type===`channel`||a.type===`state`)&&(s.pop(),c=s.join(`.`),n[c]&&(n[c].type===`channel`||n[c].type===`folder`)?(s.pop(),d=s.join(`.`),(!n[d]||n[d].type!==`device`&&n[c].type!==`folder`)&&(d=void 0)):c=void 0);let f=l.find(e=>{var t,r,a;return(t=n[e].common.members)!=null&&t.includes(i)||c&&(r=n[e].common.members)!=null&&r.includes(c)?!0:d&&((a=n[e].common.members)==null?void 0:a.includes(d))});f&&(o.room=fe(n[f].common.name,t));let m=u.find(e=>{var t,r,a;return(t=n[e].common.members)!=null&&t.includes(i)||c&&(r=n[e].common.members)!=null&&r.includes(c)?!0:d&&((a=n[e].common.members)==null?void 0:a.includes(d))});m&&(o.function=fe(n[m].common.name,t)),p.push(o)})});for(let e=0;e<p.length;e++){let r=p[e];if(r.type===`state`||r.type===`channel`){let e=r.id.split(`.`);e.pop();let i=n[e.join(`.`)];if(i&&(i.type===`channel`||i.type===`device`||i.type===`folder`)){var m,h;r.name=fe(((m=i.common)==null?void 0:m.name)||r.name,t),e.pop();let a=n[e.join(`.`)];if((a==null?void 0:a.type)===`device`&&(h=a.common)!=null&&h.icon){var _;r.name=fe(((_=a.common)==null?void 0:_.name)||r.name,t)}}else{var v;r.name=fe((i==null||(v=i.common)==null?void 0:v.name)||r.name,t)}}}return Y=p,p}async function me(){return X||(X=(await G).default,X)}function he(){return ie[g.getLanguage()]||`English`}function ge(e){return`You write ioBroker JavaScript adapter scripts.
3
+ Copy EXACTLY this syntax. Do NOT change the callback signature.
4
+ IMPORTANT: Write all code at top level. NEVER use console.log (use log instead). NEVER define functions with the function keyword.
5
+
6
+ // CORRECT: on() always has ONE callback argument called obj
7
+ on('zigbee.0.sensor.state', (obj) => {
8
+ // obj.state.val = the new value (boolean or number)
9
+ // obj.id = the state ID that changed
10
+ setState('zigbee.0.lamp.state', obj.state.val);
11
+ log('Changed to ' + obj.state.val);
12
+ });
13
+
14
+ // CORRECT: on() with filter
15
+ on({id: /zigbee\\.0\\..*\\.state$/, change: 'ne'}, (obj) => {
16
+ if (obj.state.val === true) {
17
+ setState('zigbee.0.other.state', true);
18
+ }
19
+ });
20
+
21
+ // Other correct examples:
22
+ setState('id', true);
23
+ setState('id', 50);
24
+ const val = getState('id').val;
25
+ schedule('0 7 * * *', () => { log('runs daily at 07:00'); });
26
+ schedule('0 22 * * *', () => { setState('id', false); });
27
+
28
+ // CORRECT Telegram: always use sendTo, NEVER setState on telegram
29
+ sendTo('telegram.0', 'send', {text: 'Alert: ' + someValue});
30
+
31
+ // CORRECT httpGet: res.data is a STRING, parse JSON with JSON.parse
32
+ httpGet('https://api.example.com/data', (err, res) => {
33
+ const data = JSON.parse(res.data);
34
+ log('Temperature: ' + data.main.temp);
35
+ });
36
+
37
+ $('state[state.id=*.state](rooms=Room)').each((id) => { setState(id, false); });
38
+ createState('name', 0, {type: 'number', name: 'Name'});
39
+ // CORRECT: one-time delayed action (turn off after 5 minutes = 300000ms)
40
+ setStateDelayed('zigbee.0.lamp.state', false, false, 5 * 60 * 1000);
41
+ log(formatDate(new Date(), 'DD.MM.YYYY hh:mm'));
42
+
43
+ WRONG: on('id', (id, state) => {}) CORRECT: on('id', (obj) => {})
44
+ WRONG: set('id', true) CORRECT: setState('id', true)
45
+ WRONG: adapter.setState('id', true) CORRECT: setState('id', true)
46
+ WRONG: obj.val or newState.val CORRECT: obj.state.val
47
+ WRONG: on('change', {id: 'x'}, cb) CORRECT: on({id: 'x', change: 'ne'}, cb)
48
+ WRONG: setState('telegram.0', text) CORRECT: sendTo('telegram.0', 'send', {text: text})
49
+ WRONG: res.body.main.temp CORRECT: JSON.parse(res.data).main.temp
50
+ WRONG: function myFunc() {} CORRECT: write code directly, no function definitions
51
+ WRONG: setTimeout(fn, ms) CORRECT: setStateDelayed(id, val, false, ms) for one-time delay
52
+ WRONG: schedule('*/5 * * * *', fn) for one-time delay. schedule() is ONLY for recurring tasks
53
+ Values are boolean (true/false) or numbers, NEVER strings like 'ON'/'OFF'.
54
+ NEVER use: function keyword, require, import, setInterval, setTimeout, console.log, debug().
55
+
56
+ All available functions (use syntax from examples above):
57
+ on(pattern, (obj)=>{}) | once(pattern, (obj)=>{}) | unsubscribe(handler)
58
+ setState(id, val) | getState(id).val | setStateChanged(id, val) | setStateDelayed(id, val, ack, ms) | clearStateDelayed(id)
59
+ existsState(id) | existsObject(id) | getObject(id) | setObject(id, obj) | extendObject(id, obj) | deleteObject(id)
60
+ createState(name, initVal, {type,name,role}) | deleteState(name) | createAlias(name, alias)
61
+ schedule(cron, ()=>{}) | clearSchedule(obj) | scheduleById(id, (obj)=>{}) | getSchedules()
62
+ sendTo(adapter, cmd, msg) | sendToHost(host, cmd, msg)
63
+ $('selector').each((id)=>{}) | $('selector').setState(val) | $('selector').getState()
64
+ log(text) | formatDate(date, 'DD.MM.YYYY hh:mm') | formatTimeDiff(ms) | formatValue(val, decimals)
65
+ getDateObject(str) | getAstroDate(pattern) | isAstroDay() | compareTime(start, end, op)
66
+ exec(cmd, (err,stdout,stderr)=>{}) | httpGet(url, (err,res)=>{}) | httpPost(url, data, (err,res)=>{})
67
+ readFile(adapter, name, (err,data)=>{}) | writeFile(adapter, name, data, cb) | delFile(adapter, name, cb)
68
+ onFile(id, name, withFile, cb) | offFile(id, name) | onStop(cb, timeout)
69
+ getHistory(inst, {id,start,end,aggregate,count}, cb) | getEnums(name) | getIdByName(name)
70
+ wait(ms) | toInt(val) | toFloat(val) | toBoolean(val)
71
+ messageTo(target, data) | onMessage(name, cb) | onLog(severity, cb)
72
+ runScript(name) | startScript(name) | stopScript(name) | isScriptActive(name)
73
+
74
+ Write comments in ${e}. Put code in a \`\`\`javascript code block.`}function _e(e){return`You generate ioBroker Blockly XML blocks. Return Blockly XML in a \`\`\`xml code block.
75
+ Use EXACT state IDs from the plan. Write text/comments in ${e}.
76
+
77
+ IMPORTANT RULES:
78
+ - Return ONLY the inner blocks (no <xml> wrapper needed)
79
+ - Use the exact block types shown below
80
+ - State IDs must be full paths like "zigbee2mqtt.0.0x1234.state"
81
+ - Values are boolean (true/false) or numbers, NEVER strings like "ON"/"OFF"
82
+ - For Telegram use sendto_custom block, NEVER setState on telegram
83
+
84
+ ## Block Templates
85
+
86
+ ### Trigger: on_ext (react to state changes)
87
+ <block type="on_ext" x="0" y="0">
88
+ <mutation xmlns="http://www.w3.org/1999/xhtml" items="1"></mutation>
89
+ <field name="CONDITION">ne</field>
90
+ <field name="ACK_CONDITION"></field>
91
+ <value name="OID0">
92
+ <shadow type="field_oid"><field name="oid">STATE_ID_HERE</field></shadow>
93
+ </value>
94
+ <statement name="STATEMENT">
95
+ <!-- actions here -->
96
+ </statement>
97
+ </block>
98
+
99
+ ### Schedule: schedule (cron-based)
100
+ <block type="schedule" x="0" y="0">
101
+ <field name="SCHEDULE">0 7 * * *</field>
102
+ <statement name="STATEMENT">
103
+ <!-- actions here -->
104
+ </statement>
105
+ </block>
106
+
107
+ ### Set State: control
108
+ <block type="control">
109
+ <mutation xmlns="http://www.w3.org/1999/xhtml" delay_input="false"></mutation>
110
+ <field name="OID">STATE_ID_HERE</field>
111
+ <field name="WITH_DELAY">FALSE</field>
112
+ <value name="VALUE">
113
+ <block type="logic_boolean"><field name="BOOL">TRUE</field></block>
114
+ </value>
115
+ </block>
116
+
117
+ ### Get State Value: get_value
118
+ <block type="get_value">
119
+ <field name="ATTR">val</field>
120
+ <field name="OID">STATE_ID_HERE</field>
121
+ </block>
122
+
123
+ ### Log: debug
124
+ <block type="debug">
125
+ <field name="Severity">log</field>
126
+ <value name="TEXT">
127
+ <shadow type="text"><field name="TEXT">Message here</field></shadow>
128
+ </value>
129
+ </block>
130
+
131
+ ### SendTo (Telegram): sendto_custom
132
+ <block type="sendto_custom">
133
+ <mutation xmlns="http://www.w3.org/1999/xhtml" items="1"></mutation>
134
+ <field name="INSTANCE">telegram.0</field>
135
+ <field name="COMMAND">send</field>
136
+ <field name="LOG"></field>
137
+ <value name="ARG0">
138
+ <block type="text"><field name="TEXT">Message text</field></block>
139
+ </value>
140
+ <value name="ATTR0">
141
+ <block type="text"><field name="TEXT">text</field></block>
142
+ </value>
143
+ </block>
144
+
145
+ ### Timeout: timeouts_settimeout
146
+ <block type="timeouts_settimeout">
147
+ <field name="NAME">timeout1</field>
148
+ <field name="DELAY">5000</field>
149
+ <field name="UNIT">ms</field>
150
+ <statement name="STATEMENT">
151
+ <!-- delayed actions -->
152
+ </statement>
153
+ </block>
154
+
155
+ ### If/Else: controls_if
156
+ <block type="controls_if">
157
+ <mutation else="1"></mutation>
158
+ <value name="IF0">
159
+ <block type="logic_compare">
160
+ <field name="OP">EQ</field>
161
+ <value name="A"><block type="get_value"><field name="ATTR">val</field><field name="OID">STATE_ID</field></block></value>
162
+ <value name="B"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></value>
163
+ </block>
164
+ </value>
165
+ <statement name="DO0"><!-- then --></statement>
166
+ <statement name="ELSE"><!-- else --></statement>
167
+ </block>
168
+
169
+ ### Number value
170
+ <block type="math_number"><field name="NUM">0</field></block>
171
+
172
+ ### Text value
173
+ <block type="text"><field name="TEXT">hello</field></block>
174
+
175
+ ### Boolean value
176
+ <block type="logic_boolean"><field name="BOOL">TRUE</field></block>
177
+
178
+ ### Comparison: logic_compare
179
+ <block type="logic_compare">
180
+ <field name="OP">EQ</field>
181
+ <!-- OP can be: EQ, NEQ, LT, LTE, GT, GTE -->
182
+ <value name="A"><!-- left side --></value>
183
+ <value name="B"><!-- right side --></value>
184
+ </block>
185
+
186
+ ## Common Patterns
187
+
188
+ ### Turn on light when sensor triggers:
189
+ <block type="on_ext" x="0" y="0">
190
+ <mutation xmlns="http://www.w3.org/1999/xhtml" items="1"></mutation>
191
+ <field name="CONDITION">ne</field>
192
+ <field name="ACK_CONDITION"></field>
193
+ <value name="OID0">
194
+ <shadow type="field_oid"><field name="oid">zigbee2mqtt.0.0xSENSOR.occupancy</field></shadow>
195
+ </value>
196
+ <statement name="STATEMENT">
197
+ <block type="controls_if">
198
+ <value name="IF0">
199
+ <block type="logic_compare">
200
+ <field name="OP">EQ</field>
201
+ <value name="A"><block type="get_value"><field name="ATTR">val</field><field name="OID">zigbee2mqtt.0.0xSENSOR.occupancy</field></block></value>
202
+ <value name="B"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></value>
203
+ </block>
204
+ </value>
205
+ <statement name="DO0">
206
+ <block type="control">
207
+ <mutation xmlns="http://www.w3.org/1999/xhtml" delay_input="false"></mutation>
208
+ <field name="OID">zigbee2mqtt.0.0xLAMP.state</field>
209
+ <field name="WITH_DELAY">FALSE</field>
210
+ <value name="VALUE"><block type="logic_boolean"><field name="BOOL">TRUE</field></block></value>
211
+ </block>
212
+ </statement>
213
+ </block>
214
+ </statement>
215
+ </block>
216
+
217
+ Write comments in ${e}. Put blocks in a \`\`\`xml code block.`}function ve(e){let t=e;return t=t.replace(/<think>[\s\S]*?<\/think>/gi,``),t=t.replace(/<\|endoftext\|>/g,``),t=t.replace(/<\|im_start\|>[\s\S]*?<\|im_end\|>/g,``),t=t.replace(/<\|im_start\|>[\s\S]*/g,``),t.trim()}var ye=[{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 be(e){return e&&typeof e==`object`?e.en||e.de||``:e||``}function xe(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=be(i.name).toLowerCase();if(a&&a.includes(r))return!0;let o=(i.role||``).toLowerCase();return!!(o&&o.includes(r))}async function Se(e,t,n=20,r){let i=await de(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||!xe(e,r,t))continue;let l=r.common,u={id:e,type:s,name:be(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 Ce(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 we=new Set([`channel`,`device`,`folder`,`adapter`,`instance`,`enum`,`meta`]),Te=50;async function Ee(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:be((n=t.common)==null?void 0:n.name),common:t.common})}}catch{}}if(o.length>0&&(i.parents=o),we.has(r.type)){let n=await de(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:be(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>=Te){o=!0;break}}r.length>0&&(i.children=r,o&&(i.childrenTruncated=!0,i.childrenHint=`Only the first ${Te} 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 De(e){return N(e)||e}function Oe(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?De(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(`
218
+ `),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 ke(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?De(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 Ae(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 $(){return JSON.stringify({error:`Editor is not available. This tool requires the script editor to be open.`})}async function je(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 Me(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 Se(e,a.query,a.max_results||20,a.object_type);case`get_state_value`:return Ce(e,a.id);case`get_object_info`:return Ee(e,a.id);case`search_scripts`:return Oe(n||[],a.query,a.max_results||10);case`read_script`:return ke(n||[],a.id);case`list_scripts`:return Ae(n||[]);case`run_script`:return je(e,i,a);case`get_editor_selection`:{if(!(r!=null&&r.getSelection))return $();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()}):$();case`get_cursor_position`:{if(!(r!=null&&r.getCursorPosition))return $();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 $();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 $();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 $();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 $();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 $();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 $();let e=r.getDiagnostics();return JSON.stringify({count:e.length,diagnostics:e})}case`get_document_symbols`:{if(!(r!=null&&r.getSymbols))return $();let e=await r.getSymbols();return JSON.stringify({count:e.length,symbols:e})}default:return JSON.stringify({error:`Unknown tool: ${t.function.name}`})}}var Ne=0;function Pe(){return`msg_${Date.now()}_${++Ne}`}function Fe(e){let{socket:n,runningInstances:r,currentCode:i,currentLanguage:a,allScripts:o,editorApi:s,currentScriptId:c}=e,l=w((e,t,n)=>e===`none`||!n?null:{range:t,scriptId:c||``,scriptVersion:(i||``).length,kind:e,originalText:n},[c,i]),[u,d]=b(()=>{try{let e=window.localStorage.getItem(`Editor.aiChatMessages`);return e?JSON.parse(e):[]}catch{return[]}}),f=w(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]=b(!1),[_,v]=b(null),[y,x]=b(window.localStorage.getItem(`Editor.aiChatMode`)||`agent`),S=w(e=>{x(e),window.localStorage.setItem(`Editor.aiChatMode`,e)},[]),[T,E]=b(null),[D,O]=b(window.localStorage.getItem(`openai-model`)||``),[k,ee]=b([]),[A,j]=b({}),[M,N]=b(!0),[I,te]=b(null),L=C(null),R=C(null),z=C(null),ne=C(null),B=w(e=>{O(e),window.localStorage.setItem(`openai-model`,e)},[]),V=w(async()=>{N(!0),te(null);try{let e=await ce(n,r);if(ee(e.models),j(e.providerMap),e.models.length>0){let t=window.localStorage.getItem(`openai-model`);t&&e.models.includes(t)?O(t):O(e.models[0])}e.errors.length>0&&te(e.errors.join(`; `))}catch(e){te(String(e))}N(!1)},[n,r]);h(()=>{V()},[V]);let H=w(e=>{let t=!1,n=!1,r=[],i=!1,a=/@([\w/äöüÄÖÜß-]+)/g,s;for(;(s=a.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,o&&o.length>0){let e=s[1].replace(/\//g,`.`).toLowerCase(),t=e.split(`.`),n=o.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=o.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}},[o]),re=w(async(e,t,s)=>{ne.current||=await me(),L.current||=await Q(n,r);let c=he(),l=a===`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.
219
+
220
+ ioBroker object hierarchy: adapter.instance.device.channel.state
221
+ - A "state" is a single datapoint (e.g. zigbee2mqtt.0.0x1234.temperature)
222
+ - A "channel" groups related states (e.g. zigbee2mqtt.0.0x1234 contains temperature, humidity, battery)
223
+ - A "device" groups channels (e.g. zigbee2mqtt.0.0x1234)
224
+ - The channel/device often has the human-readable name (e.g. "Living Room Sensor")
225
+ 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.
226
+
227
+ 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.
228
+
229
+ Available API and syntax rules:
230
+ ${ne.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."),(t||e)&&(z.current||=await pe(n),d+=`\n\nAvailable smart home devices:\n${JSON.stringify(z.current,null,0)}`),!u&&i)if(l){let e=i.indexOf(`%%BLOCKLY_XML%%`),t=e===-1?i:i.substring(0,e).trim(),n=e===-1?``:i.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, ${a||`javascript`}):\n\`\`\`${a||`javascript`}\n${i}\n\`\`\``;if(e&&o&&o.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${F(o,!0)}`;else if(s.length>0&&o){let e=o.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${F(e,!0)}`)}return l&&(d+=`\n\n${_e(c)}`),[{role:`system`,content:d}]},[n,r,i,a,o]),U=w(async e=>{if(!e.trim()||p)return;let t=A[D];if(!t){E(g.t(`Please select a valid model`));return}let i=L.current||await Q(n,r);if(L.current=i,!i){E(g.t(`No API keys configured`));return}let o=Object.keys(r)[0];if(!o){E(g.t(`No running javascript instance found`));return}let s=t===`custom`&&i.gptBaseUrl||``,c={id:Pe(),role:`user`,content:e,timestamp:Date.now()},l={id:Pe(),role:`assistant`,content:`⏳ ${g.t(`Generating plan...`)}`,timestamp:Date.now()};f(e=>[...e,c,l]),m(!0),E(null);try{let r=he();z.current||=await pe(n);let i=z.current||[],c=`Devices in my smart home:\n${JSON.stringify(i)}\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 le(n,o,{messages:[{role:`user`,content:c}],model:D,provider:t,baseUrl:s});if(l.error){E(l.error),f(e=>e.slice(0,-2)),m(!1);return}let u=ve(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:`📋 **${g.t(`Plan`)}:**\n${u}`}),t});let d={id:Pe(),role:`assistant`,content:`⏳ ${g.t(`Generating code...`)}`,timestamp:Date.now()};f(e=>[...e,d]);let p=a===`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 ${r}. 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 ${r}. Put the code in a \`\`\`javascript code block. You may add a short explanation before or after the code.`,_=p?_e(r):ge(r),y=await le(n,o,{messages:[{role:`system`,content:_},{role:`user`,content:h}],model:D,provider:t,baseUrl:s});if(y.error){E(y.error),f(e=>e.slice(0,-1)),m(!1);return}let b=ve(y.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:b}),t}),v(`${g.t(`devices`)}: ${i.length}`)}catch(e){E(String(e)),f(e=>e.slice(0,-1))}m(!1)},[D,A,p,n,r,a,f]),W=w(async e=>{if(y===`code`)return U(e);if(!e.trim()||p)return;let t=A[D];if(!t){E(g.t(`Please select a valid model`));return}let i=L.current||await Q(n,r);if(L.current=i,!i){E(g.t(`No API keys configured`));return}let a=Object.keys(r)[0];if(!a){E(g.t(`No running javascript instance found`));return}let c=R.current;if(R.current=null,!c)try{var d;let e=s==null||(d=s.getSelection)==null?void 0:d.call(s);e&&e.text&&(c=l(`selection`,e.range,e.text))}catch{}let h={id:Pe(),role:`user`,content:e,timestamp:Date.now(),sourceRange:c},_={id:Pe(),role:`assistant`,content:``,timestamp:Date.now(),sourceRange:c};f(e=>[...e,h,_]),m(!0),E(null);let{cleanMessage:b,mentionedScriptIds:x,includeAll:S,includeDevices:C}=H(e),w=[];if(S)w.push(`${g.t(`all scripts`)} (${(o==null?void 0:o.length)||0})`);else if(x.length>0){let e=x.map(e=>e.replace(/^script\.js\./,``));w.push(e.join(`, `))}else w.push(g.t(`current script`));C&&w.push(g.t(`devices`)),v(`${g.t(`Context`)}: ${w.join(` + `)}`);let T=await re(S,C,x),O=t===`custom`&&i.gptBaseUrl||``,k=b||e;if(o&&o.length>0){let e=k.match(/\b[\w-]+\.\d+\.[\w.-]+/g);if(e){let t=[];for(let n of new Set(e)){let e=P(o,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(`
231
+ `)}`)}t.length>0&&(k+=`\n\n[Automatic analysis results]\n${t.join(`
232
+
233
+ `)}`)}}let ee=[...T,...u.filter(e=>e.role!==`system`).map(e=>({role:e.role,content:e.content})),{role:`user`,content:k}],j=y===`agent`;try{let e=[...ee];for(let r=0;r<5;r++){let i=await le(n,a,{messages:e,model:D,provider:t,baseUrl:O,...j?{tools:ye}:{}});if(i.error){if(j&&r===0&&i.error.toLowerCase().includes(`tool`)){let r=await le(n,a,{messages:e,model:D,provider:t,baseUrl:O});if(r.error)E(r.error),f(e=>e.slice(0,-1));else{let e=ve(r.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}E(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=ve(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`🔍 ${g.t(`Searching datapoints`)}: "${String(t.query||``)}"`;case`get_state_value`:return`📊 ${g.t(`Reading value`)}: ${String(t.id||``)}`;case`get_object_info`:return`📋 ${g.t(`Loading object info`)}: ${String(t.id||``)}`;case`search_scripts`:return`🔍 ${g.t(`Searching scripts`)}: "${String(t.query||``)}"`;case`read_script`:return`📖 ${g.t(`Reading script`)}: ${String(t.id||``)}`;case`list_scripts`:return`📂 ${g.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(`
234
+ `)}),t}),e.push({role:`assistant`,content:i.content||``,tool_calls:i.tool_calls});for(let t of i.tool_calls){let r=await Me(n,t,o,s,a);e.push({role:`tool`,tool_call_id:t.id,content:r})}}}catch(e){E(String(e)),f(e=>e.slice(0,-1))}m(!1)},[D,A,u,p,n,r,re,H,o,y,U,f,l,s]),G=w(()=>{f([]),E(null),m(!1),v(null),ae(),window.localStorage.removeItem(`Editor.aiChatHistory`)},[f]),K=w(async(e,t)=>{let i=A[D];if(!i)return`Error: ${g.t(`Please select a valid model`)}`;let o=L.current||await Q(n,r);if(L.current=o,!o)return`Error: ${g.t(`No API keys configured`)}`;let s=Object.keys(r)[0];if(!s)return`Error: ${g.t(`No running javascript instance found`)}`;let c=i===`custom`&&o.gptBaseUrl||``,l=a||`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=t?`Code from my editor:\n\n\`\`\`${l===`blockly`?`xml`:l}\n${t}\n\`\`\`\n\n${e}`:e;try{let e=await le(n,s,{messages:[{role:`system`,content:u},{role:`user`,content:d}],model:D,provider:i,baseUrl:c});return e.error?`Error: ${e.error}`:e.content||``}catch(e){return`Error: ${e.message||String(e)}`}},[D,A,r,n,a]);return{messages:u,isLoading:p,error:T,model:D,availableModels:k,modelProviderMap:A,modelsLoading:M,modelsError:I,lastContextInfo:_,mode:y,setMode:S,setModel:B,sendMessage:W,triggerAiAction:w(e=>{e.range&&e.code?R.current=l(e.kind||`codelens`,e.range,e.code):R.current=null,t(async()=>{let{buildActionPrompt:e}=await import(`./aiPromptBuilder-Bs27qOHT.js`).then(e=>e.t);return{buildActionPrompt:e}},__vite__mapDeps([0,1]),import.meta.url).then(({buildActionPrompt:t})=>{let n=t({action:e.action,code:e.code,language:a||`javascript`,diagnostic:e.diagnostic,question:e.question,rangeLabel:e.rangeLabel});n?W(n):R.current=null}).catch(()=>{R.current=null,E(g.t(`Failed to build AI action prompt`))})},[W,a,l]),askInline:K,clearChat:G,retryLoadModels:V}}j();var Ie=({code:e,language:t,themeType:i,onInsertCode:a,onShowDiff:s,sourceRange:c})=>{let l=C(null);h(()=>{var n;let r=window.monaco;if(!l.current||!(r!=null&&(n=r.editor)!=null&&n.colorize))return;let a=t===`ts`||t===`typescript`?`typescript`:t||`javascript`;r.editor.colorize(e,a,{theme:i===`dark`?`vs-dark`:`vs`}).then(e=>{l.current&&(l.current.innerHTML=e)})},[e,t,i]);let u=w(()=>{navigator.clipboard.writeText(e)},[e]);return f(o,{sx:{position:`relative`,my:1,borderRadius:1,overflow:`hidden`,border:`1px solid`,borderColor:`divider`},children:[f(o,{sx:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,px:1,py:.5,bgcolor:`action.hover`,borderBottom:`1px solid`,borderColor:`divider`},children:[r(o,{sx:{fontSize:`0.75rem`,color:`text.secondary`,textTransform:`uppercase`},children:t||`javascript`}),f(o,{children:[r(n,{title:g.t(`Copy`),children:r(x,{size:`small`,onClick:u,children:r(y,{sx:{fontSize:16}})})}),a&&r(n,{title:g.t(`Insert into editor`),children:r(x,{size:`small`,onClick:()=>a(e),children:r(R,{sx:{fontSize:16}})})}),s&&r(n,{title:g.t(`Show as diff`),children:r(x,{size:`small`,onClick:()=>s(e,c),children:r(B,{sx:{fontSize:16}})})})]})]}),r(`pre`,{ref:l,style:{margin:0,padding:`8px 12px`,overflow:`auto`,maxHeight:400,fontSize:`13px`,fontFamily:`'Cascadia Code', 'Fira Code', 'Consolas', monospace`,backgroundColor:i===`dark`?`#1e1e1e`:`#f8f8f8`,color:i===`dark`?`#d4d4d4`:`#333`},children:e})]})};j();var Le=({xml:e,themeType:t})=>{let n=C(null),i=C(null),[a,s]=b(60),c=C(!1);return h(()=>{c.current&&(c.current=!1,requestAnimationFrame(()=>{let e=window.Blockly,t=i.current;e&&t&&(e.svgResize(t),t.scrollCenter())}))},[a]),h(()=>{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:t===`dark`?I():`classic`,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]),r(o,{ref:n,sx:{width:`100%`,height:a,minHeight:60,borderRadius:1,overflow:`hidden`,border:`1px solid`,borderColor:`divider`}})};j();function Re(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 ze(e){let t=[],n=/(\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`)/g,i=0,a,o=0;for(;(a=n.exec(e))!==null;)a.index>i&&t.push(e.substring(i,a.index)),a[2]?t.push(r(`strong`,{children:a[2]},o++)):a[3]?t.push(r(`em`,{children:a[3]},o++)):a[4]&&t.push(r(`code`,{className:`ai-chat-inline-code`,style:{padding:`2px 6px`,borderRadius:4,fontSize:`0.85em`,fontFamily:`'Cascadia Code', 'Fira Code', 'Consolas', monospace`},children:a[4]},o++)),i=a.index+a[0].length;return i<e.length&&t.push(e.substring(i)),t}function Be(e){return e.trim().startsWith(`|`)&&e.trim().endsWith(`|`)}function Ve(e){return/^\|[\s:]*-+[\s:|-]*\|$/.test(e.trim())}function He(e,t,n){let i=t.palette.mode===`dark`,a=e=>e.trim().replace(/^\||\|$/g,``).split(`|`).map(e=>e.trim()),s=a(e[0]),c=e.slice(2).map(a);return r(o,{sx:{overflowX:`auto`,my:1},children:f(`table`,{style:{borderCollapse:`collapse`,width:`100%`,fontSize:`0.8rem`,color:t.palette.text.primary},children:[r(`thead`,{children:r(`tr`,{children:s.map((e,n)=>r(`th`,{style:{border:`1px solid ${t.palette.divider}`,padding:`6px 10px`,backgroundColor:i?t.palette.grey[800]:t.palette.grey[100],color:t.palette.text.primary,fontWeight:600,textAlign:`left`},children:ze(e)},n))})}),r(`tbody`,{children:c.map((e,n)=>r(`tr`,{style:{backgroundColor:n%2==1?i?t.palette.grey[900]:t.palette.grey[50]:void 0},children:e.map((e,n)=>r(`td`,{style:{border:`1px solid ${t.palette.divider}`,padding:`6px 10px`,color:t.palette.text.primary},children:ze(e)},n))},n))})]})},n)}function Ue(e,t){let n=e.split(`
235
+ `),i=[],a=0,o=0;for(;o<n.length;){let e=n[o].trim();if(e===``){o++;continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(e)){i.push(r(`hr`,{style:{border:`none`,borderTop:`1px solid ${t.palette.divider}`,margin:`8px 0`}},a++)),o++;continue}let s=e.match(/^(#{1,4})\s+(.+)$/);if(s){let e=s[1].length;i.push(r(`div`,{style:{fontWeight:600,fontSize:[`1.2em`,`1.1em`,`1em`,`0.95em`][e-1],margin:`8px 0 4px`},children:ze(s[2])},a++)),o++;continue}if(Be(e)&&o+1<n.length&&Ve(n[o+1].trim())&&o+2<n.length){let e=[n[o],n[o+1]],r=o+2;for(;r<n.length&&Be(n[r]);)e.push(n[r]),r++;i.push(He(e,t,a++)),o=r;continue}if(/^[-*+]\s/.test(e)){let e=[];for(;o<n.length&&/^\s*[-*+]\s/.test(n[o]);)e.push(n[o].replace(/^\s*[-*+]\s/,``).trim()),o++;i.push(r(`ul`,{style:{margin:`4px 0`,paddingLeft:20},children:e.map((e,t)=>r(`li`,{children:ze(e)},t))},a++));continue}if(/^\d+[.)]\s/.test(e)){let e=[];for(;o<n.length&&/^\s*\d+[.)]\s/.test(n[o]);)e.push(n[o].replace(/^\s*\d+[.)]\s/,``).trim()),o++;i.push(r(`ol`,{style:{margin:`4px 0`,paddingLeft:20},children:e.map((e,t)=>r(`li`,{children:ze(e)},t))},a++));continue}i.push(r(`div`,{children:ze(e)},a++)),o++}return i}var We=({message:e,themeType:t,currentLanguage:n,onInsertCode:i,onShowDiff:a,onApplyCode:s})=>{let c=e.role===`user`,u=l(),p=c?t===`dark`?u.palette.primary.dark:u.palette.primary.main:t===`dark`?u.palette.secondary.dark:u.palette.secondary.main,m=u.palette.getContrastText(p),h=_(()=>Re(e.content),[e.content]),v=(e,t)=>!!(e===`xml`||e===`blockly`||n===`blockly`&&t&&/<block\s+type=/.test(t));return f(o,{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:p,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:[r(d,{sx:{width:28,height:28,bgcolor:p,color:m,flexShrink:0,mt:.5},children:r(c?V:U,{sx:{fontSize:18}})}),r(o,{sx:{flex:1,minWidth:0,fontSize:`0.875rem`,lineHeight:1.6},children:h.map((n,c)=>n.type===`code`?v(n.language,n.content)?f(o,{sx:{my:1},children:[r(Le,{xml:n.content,themeType:t}),f(o,{sx:{display:`flex`,gap:.5,mt:.5},children:[s&&r(M,{size:`small`,variant:`contained`,color:`primary`,startIcon:r(H,{sx:{fontSize:14}}),onClick:()=>s(n.content),sx:{textTransform:`none`,fontSize:`0.75rem`},children:g.t(`Apply blocks`)}),i&&r(M,{size:`small`,variant:`outlined`,startIcon:r(R,{sx:{fontSize:14}}),onClick:()=>i(n.content),sx:{textTransform:`none`,fontSize:`0.75rem`},children:g.t(`Insert blocks`)})]})]},c):r(Ie,{code:n.content,language:n.language||`javascript`,themeType:t,onInsertCode:i,onShowDiff:a,sourceRange:e.sourceRange||null},c):r(o,{sx:{wordBreak:`break-word`,color:u.palette.text.primary},children:Ue(n.content,u)},c))})]})};j();function Ge(){return[{id:`@all`,label:g.t(`mention @all`),descriptionKey:`All scripts`},{id:`@devices`,label:g.t(`mention @devices`),descriptionKey:`Smart home devices`}]}function Ke({provider:e,isDark:t}){return K[e]?r(`img`,{src:`./img/${e}.svg`,alt:e,style:{...q,...t?{filter:`invert(0.85)`}:{}},onError:e=>{e.target.style.display=`none`}}):null}function qe(){try{let e=window.localStorage.getItem(`Editor.aiChatHistory`);return e?JSON.parse(e):[]}catch{return[]}}var Je=({onSend:e,disabled:t,themeType:s,hasSelection:l,selectionText:d,allScripts:m,model:y,availableModels:T,modelProviderMap:E,modelsLoading:D,onModelChange:k,mode:j,onModeChange:M,currentLanguage:N})=>{let[P,F]=b(``),[I,R]=b(!1),[z,B]=b(``),[V,H]=b(0),U=C(null),W=C(-1),G=C(qe()),K=C(-1),q=C(``),ie=_(()=>{let e=Ge().map(e=>({...e,description:g.t(e.descriptionKey)}));if(m)for(let t of m){let n=t.id.replace(/^script\.js\./,``).replace(/\./g,`/`);e.push({id:`@${n}`,label:`@${n}`,description:`${t.name} [${t.enabled?`active`:`inactive`}]`})}return e},[m]),J=_(()=>{if(!z)return ie;let e=z.toLowerCase();return ie.filter(t=>t.id.toLowerCase().includes(e)||t.description.toLowerCase().includes(e))},[ie,z]);h(()=>{H(0)},[z]);let Y=w(()=>{let n=P.trim();if(!n||t)return;let r=n,i=L(n);if(i){let e=l&&d?d:``,t=te({action:i.action,code:e,language:N||`javascript`,question:i.action===`ask`?i.rest:void 0,diagnostic:i.action===`fix`&&i.rest||void 0});t&&(r=t)}else l&&d&&(r=`[Selected code in editor]\n\`\`\`\n${d}\n\`\`\`\n\n${n}`);G.current.push(n),K.current=-1,q.current=``;try{let e=G.current.slice(-50);window.localStorage.setItem(`Editor.aiChatHistory`,JSON.stringify(e))}catch{}e(r),F(``),R(!1),requestAnimationFrame(()=>{var e;return(e=U.current)==null?void 0:e.focus()})},[P,t,e,l,d,N]),X=w(e=>{let t=W.current,n=U.current;if(t<0){let t=P?`${P}${e} `:`${e} `;F(t),R(!1),B(``),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),R(!1),B(``),W.current=-1,setTimeout(()=>{if(n){let t=r.length+e.length+1;n.focus(),n.setSelectionRange(t,t)}},0)},[P]),Z=w(()=>{W.current=-1,B(``),R(e=>!e)},[]),ae=w(e=>{let t=e.target.value;F(t);let n=e.target.selectionStart??t.length,r=t.substring(0,n).match(/@([\w/äöüÄÖÜß]*)$/);r?(W.current=n-r[0].length,B(r[1]),R(!0)):(R(!1),B(``))},[]),Q=w(e=>{if(I&&J.length>0){if(e.key===`ArrowDown`){e.preventDefault(),H(e=>(e+1)%J.length);return}if(e.key===`ArrowUp`){e.preventDefault(),H(e=>(e-1+J.length)%J.length);return}if(e.key===`Enter`||e.key===`Tab`){e.preventDefault(),X(J[V].id);return}if(e.key===`Escape`){e.preventDefault(),R(!1);return}}if(e.key===`ArrowUp`&&!I&&G.current.length>0){let t=U.current,n=!t||t.selectionStart===0,r=!P.includes(`
236
+ `);if(n&&r){e.preventDefault(),K.current===-1?(q.current=P,K.current=G.current.length-1):K.current>0&&K.current--,F(G.current[K.current]);return}}if(e.key===`ArrowDown`&&!I&&K.current>=0){let t=U.current,n=!t||t.selectionStart===P.length,r=!P.includes(`
237
+ `);if(n&&r){e.preventDefault(),K.current<G.current.length-1?(K.current++,F(G.current[K.current])):(K.current=-1,F(q.current));return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),Y())},[Y,I,J,V,X,P]);return f(o,{sx:{borderTop:`1px solid`,borderColor:`divider`,position:`relative`},children:[I&&J.length>0&&r(u,{elevation:4,sx:{position:`absolute`,bottom:`100%`,left:8,right:8,maxHeight:200,overflow:`auto`,zIndex:10,mb:.5},children:r(S,{dense:!0,disablePadding:!0,children:J.slice(0,15).map((e,t)=>r(v,{selected:t===V,onClick:()=>X(e.id),sx:{py:.25,minHeight:32},children:r(O,{primary:e.label,secondary:e.description,slotProps:{primary:{sx:{fontSize:`0.8rem`,fontWeight:500}},secondary:{sx:{fontSize:`0.7rem`}}}})},e.id))})}),j===`code`&&r(a,{label:`${g.t(`mention @devices`)} — ${g.t(`Smart home devices`)}`,size:`small`,variant:`outlined`,sx:{mx:1,mt:.5,maxWidth:`calc(100% - 16px)`}}),l&&d&&r(a,{icon:r(p,{sx:{fontSize:14}}),label:g.t(`Selected code as context`),size:`small`,variant:`outlined`,sx:{mx:1,mt:.5,maxWidth:`calc(100% - 16px)`}}),f(o,{sx:{mx:1,mt:.5,mb:.5,border:`1px solid`,borderColor:`divider`,borderRadius:1.5,overflow:`hidden`,"&:focus-within":{borderColor:`primary.main`}},children:[r(c,{inputRef:U,fullWidth:!0,multiline:!0,maxRows:6,placeholder:g.t(`Ask about your script...`),value:P,onChange:ae,onKeyDown:Q,disabled:t,onBlur:()=>{setTimeout(()=>R(!1),200)},variant:`standard`,slotProps:{input:{disableUnderline:!0}},sx:{px:1.5,pt:1,pb:.5,"& .MuiInputBase-root":{fontSize:`0.875rem`}}}),f(o,{sx:{display:`flex`,alignItems:`center`,gap:.75,px:1,pb:.5},children:[r(n,{title:f(o,{sx:{fontSize:`0.8rem`,lineHeight:1.5,maxWidth:360},children:[r(o,{sx:{fontWeight:600,mb:.75},children:g.t(`AI chat mode`)}),f(o,{sx:{mb:.75},children:[f(`strong`,{children:[`💬 `,g.t(`Chat`)]}),` —`,` `,g.t(`Plain conversation. Use for questions, explanations, syntax help. Does not read or modify your scripts.`)]}),f(o,{sx:{mb:.75},children:[f(`strong`,{children:[`🤖 `,g.t(`Agent`)]}),` —`,` `,g.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".`)]}),f(o,{children:[f(`strong`,{children:[`💻 `,g.t(`Code`)]}),` —`,` `,g.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:f(ee,{value:j,onChange:e=>M(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:[r(A,{value:`chat`,sx:{fontSize:`0.75rem`},title:g.t(`Plain conversation. Best for: general questions, syntax help, concept explanations.`),children:`💬 Chat`}),r(A,{value:`agent`,sx:{fontSize:`0.75rem`},title:g.t(`For larger models with tool support. Best for: creating, editing, or analyzing scripts; finding datapoint usages; inspecting the object tree.`),children:`🤖 Agent`}),r(A,{value:`code`,sx:{fontSize:`0.75rem`},title:g.t(`For smaller models without tool support. Best for: creating new JavaScript/TypeScript or Blockly scripts from a description.`),children:`💻 Code`})]})}),r(ee,{value:y,onChange:e=>k(e.target.value),size:`small`,disabled:D||T.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:T.map(e=>f(A,{value:e,sx:{fontSize:`0.75rem`,display:`flex`,gap:.5},children:[r(Ke,{provider:E[e],isDark:s===`dark`}),e]},e))}),r(n,{title:g.t(`Mention scripts as context for the AI. Use @all for all scripts or @scriptName for a specific one.`),enterDelay:500,children:r(x,{size:`small`,onClick:Z,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:r(ne,{sx:{fontSize:16}})})}),r(o,{sx:{flex:1}}),f(i,{variant:`caption`,sx:{color:`text.disabled`,fontSize:`0.65rem`,mr:.5,whiteSpace:`nowrap`},children:[`Enter `,g.t(`to send`)]}),r(n,{title:`${g.t(`Send`)} (Enter)`,children:r(`span`,{children:r(x,{color:`primary`,onClick:Y,disabled:t||!P.trim(),size:`small`,sx:{p:.25},children:r(re,{sx:{fontSize:18}})})})})]})]})]})};j();var Ye=({socket:e,runningInstances:t,themeType:a,currentCode:s,currentLanguage:c,selectedCode:l,allScripts:u,editorApi:d,aiActionRequest:p,onAiActionConsumed:v,onRegisterInlineAsk:y,onInsertCode:b,onShowDiff:S,onApplyCode:E,currentScriptId:O,onClose:ee})=>{var A;let j=C(null),{messages:M,isLoading:N,error:P,model:F,availableModels:I,modelProviderMap:te,modelsLoading:L,modelsError:R,lastContextInfo:ne,mode:B,setMode:V,setModel:H,sendMessage:re,triggerAiAction:U,askInline:W,clearChat:G,retryLoadModels:K}=Fe(_(()=>({socket:e,runningInstances:t,currentCode:s,currentLanguage:c,allScripts:u,editorApi:d,currentScriptId:O}),[e,t,s,c,u,d,O]));h(()=>(y==null||y(W),()=>y==null?void 0:y(null)),[W,y]);let q=C(null);h(()=>{!p||q.current===p||(q.current=p,U(p),v==null||v())},[p,U,v]),h(()=>{var e;(e=j.current)==null||e.scrollIntoView({behavior:`smooth`})},[M]);let ie=w(e=>{b==null||b(e)},[b]),J=w((e,t)=>{S==null||S(e,t)},[S]),Y=w(e=>{E==null||E(e)},[E]);return f(o,{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:[f(o,{sx:{display:`flex`,alignItems:`center`,gap:1,px:1,py:.5,borderBottom:`1px solid`,borderColor:`divider`,bgcolor:a===`dark`?`grey.900`:`grey.100`,flexShrink:0},children:[r(i,{variant:`subtitle2`,sx:{fontWeight:600,flex:1,color:`text.primary`},children:g.t(`AI Chat`)}),L&&r(T,{size:16}),r(n,{title:g.t(`New chat`),children:r(x,{size:`small`,onClick:G,children:r(z,{sx:{fontSize:18}})})}),r(n,{title:g.t(`Close`),children:r(x,{size:`small`,onClick:ee,children:r(k,{sx:{fontSize:18}})})})]}),(P||R)&&r(m,{severity:`error`,sx:{m:1,py:0},action:R?r(x,{size:`small`,onClick:K,children:r(D,{sx:{fontSize:16}})}):void 0,children:P||R}),ne&&r(i,{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:ne}),f(o,{sx:{flex:1,overflow:`auto`,py:1},children:[M.length===0&&!N&&f(o,{sx:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,height:`100%`,color:`text.secondary`,px:3,textAlign:`center`},children:[r(i,{variant:`body2`,sx:{mb:1},children:g.t(`Ask questions about your script, request changes, or generate new code.`)}),f(i,{variant:`caption`,color:`text.disabled`,children:[`Enter `,g.t(`to send`),`, Shift+Enter `,g.t(`for new line`)]})]}),M.filter(e=>e.role!==`system`).map(e=>r(We,{message:e,themeType:a,currentLanguage:c,onInsertCode:ie,onShowDiff:J,onApplyCode:Y},e.id)),N&&((A=M[M.length-1])==null?void 0:A.content)===``&&f(o,{sx:{display:`flex`,alignItems:`center`,gap:1,px:2,py:1},children:[r(T,{size:16}),r(i,{variant:`caption`,color:`text.secondary`,children:g.t(`Thinking...`)})]}),r(`div`,{ref:j})]}),r(Je,{onSend:re,disabled:N||I.length===0,themeType:a,hasSelection:!!l,selectionText:l,allScripts:u,model:F,availableModels:I,modelProviderMap:te,modelsLoading:L,onModelChange:H,mode:B,onModeChange:V,currentLanguage:c})]})};export{Ye as default};
@@ -0,0 +1,2 @@
1
+ var e=[/getState\s*\(\s*['"`]$/,/setState\s*\(\s*['"`]$/,/setStateChanged\s*\(\s*['"`]$/,/setStateDelayed\s*\(\s*['"`]$/,/existsState\s*\(\s*['"`]$/,/existsObject\s*\(\s*['"`]$/,/getObject\s*\(\s*['"`]$/,/on\s*\(\s*['"`]$/,/once\s*\(\s*['"`]$/,/subscribe\s*\(\s*['"`]$/,/on\s*\(\s*\{\s*id\s*:\s*['"`]$/,/\$\s*\(\s*['"`]$/],t=null,n=null;function r(e,t){return e&&typeof e==`object`?e[t]||e.en||``:e||``}async function i(e){return t||n||(n=(async()=>{let i=window.systemLang||`en`,a=await e.getObjectViewSystem(`state`,``,`香`),o=await e.getObjectViewSystem(`enum`,``,`香`),s={},c={};for(let e of Object.keys(o)){var l;let t=o[e],n=(l=t.common)==null?void 0:l.members;if(!n)continue;let a=r(t.common.name,i);for(let t of n)e.startsWith(`enum.rooms.`)?s[t]=a:e.startsWith(`enum.functions.`)&&(c[t]=a)}let u=[];for(let e of Object.keys(a)){let t=a[e];if(!(t!=null&&t.common))continue;let n=t.common,o=r(n.name,i),l=e.split(`.`),d,f;for(let e=l.length;e>=2;e--){let t=l.slice(0,e).join(`.`);if(!d&&s[t]&&(d=s[t]),!f&&c[t]&&(f=c[t]),d&&f)break}u.push({id:e,name:o,type:n.type,role:n.role,unit:n.unit,room:d,func:f,read:n.read,write:n.write})}return t=u,n=null,u})(),n)}function a(){t=null,n=null}function o(t,n){let r=[];for(let a of[`javascript`,`typescript`]){let o=t.languages.registerCompletionItemProvider(a,{triggerCharacters:[`'`,`"`,"`",`.`],async provideCompletionItems(r,a){let o=r.getLineContent(a.lineNumber).substring(0,a.column-1);if(!e.some(e=>e.test(o)))return;let s=o.match(/['"`]([^'"`]*)$/);if(!s)return;let c=s[1],l=a.column-c.length,u=await i(n),d;if(c){let e=c.toLowerCase();d=u.filter(t=>t.id.toLowerCase().includes(e)||t.name.toLowerCase().includes(e))}else d=u;d=d.slice(0,100);let f={startLineNumber:a.lineNumber,startColumn:l,endLineNumber:a.lineNumber,endColumn:a.column};return{suggestions:d.map(e=>{let n=[];e.name&&n.push(e.name),e.room&&n.push(`Room: ${e.room}`),e.func&&n.push(`Function: ${e.func}`);let r=[];return e.role&&r.push(`Role: ${e.role}`),e.type&&r.push(`Type: ${e.type}`),e.unit&&r.push(`Unit: ${e.unit}`),r.push(`Read: ${e.read===!1?`no`:`yes`}`),r.push(`Write: ${e.write===!1?`no`:`yes`}`),{label:e.id,kind:t.languages.CompletionItemKind.Value,detail:n.join(` | `),documentation:r.join(`
2
+ `),insertText:e.id,range:f,filterText:`${e.id} ${e.name}`,sortText:e.id}})}}});r.push(o)}return{dispose:()=>{r.forEach(e=>e.dispose())}}}export{a as clearDatapointCache,o as registerDatapointProvider};
@@ -0,0 +1 @@
1
+ import{Hn as e,It as t,Lt as n,Pt as r,Un as i,bt as a,cr as o,f as s,mr as c,or as l,vt as u,yr as d,zt as f}from"./_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-CxICLr5Z.js";d();var p=({originalCode:d,modifiedCode:p,language:m,themeType:h,onAccept:g,onReject:_})=>{let v=c(null),y=c(null),b=c(null);o(()=>{let e=window.monaco;if(!e||!v.current)return;let t=e.editor.createDiffEditor(v.current,{readOnly:!1,originalEditable:!1,renderSideBySide:!0,automaticLayout:!0,theme:h===`dark`?`vs-dark`:`vs`,scrollBeyondLastLine:!1,minimap:{enabled:!1}}),n=e.editor.createModel(d,m),r=e.editor.createModel(p,m);return b.current=r,t.setModel({original:n,modified:r}),y.current=t,()=>{t.dispose(),n.dispose(),r.dispose(),y.current=null,b.current=null}},[d,p,m,h]);let x=l(()=>{var e;g(((e=b.current)==null?void 0:e.getValue())||p)},[p,g]);return i(n,{sx:{display:`flex`,flexDirection:`column`,height:`100%`,width:`100%`},children:[i(r,{variant:`dense`,sx:{minHeight:36,bgcolor:`background.paper`,borderBottom:`1px solid`,borderColor:`divider`,gap:1,flexShrink:0},children:[e(t,{variant:`subtitle2`,sx:{flex:1},children:s.t(`AI suggested changes`)}),e(f,{variant:`contained`,color:`success`,size:`small`,startIcon:e(a,{}),onClick:x,children:s.t(`Accept`)}),e(f,{variant:`outlined`,color:`error`,size:`small`,startIcon:e(u,{}),onClick:_,children:s.t(`Reject`)})]}),e(n,{ref:v,sx:{flex:1,overflow:`hidden`}})]})};export{p as default};
@@ -0,0 +1,5 @@
1
+ var e=null,t=null,n=null;function r(r,i,a){let o=[];for(let s of[`javascript`,`typescript`]){let c=r.languages.registerInlineCompletionsProvider(s,{disposeInlineCompletions(){},provideInlineCompletions(o,s,c,l){return new Promise(c=>{if(e&&=(e.cancel(),null),t&&clearTimeout(t),l.isCancellationRequested){c(void 0);return}t=setTimeout(async()=>{if(l.isCancellationRequested){c(void 0);return}let t=Object.keys(a)[0];if(!t){c(void 0);return}if(!n||Date.now()-n.ts>6e4)try{let e=await i.sendTo(t,`getAvailableAiProviders`,{});n={providers:(e==null?void 0:e.providers)||[],ts:Date.now()}}catch{c(void 0);return}let u=[`custom`,`openai`,`deepseek`,`anthropic`,`gemini`],d=``,f=``;for(let e of u){let t=n.providers.find(t=>t.provider===e);if(t){d=e===`custom`?`openai`:e,f=t.baseUrl||``;break}}if(!d){c(void 0);return}let p=window.localStorage.getItem(`openai-model`)||``,m=o.getLineCount(),h=Math.max(1,s.lineNumber-50),g=Math.min(m,s.lineNumber+10),_=``;for(let e=h;e<s.lineNumber;e++)_+=`${o.getLineContent(e)}\n`;_+=o.getLineContent(s.lineNumber).substring(0,s.column-1);let v=o.getLineContent(s.lineNumber).substring(s.column-1);for(let e=s.lineNumber+1;e<=g;e++)v+=`\n${o.getLineContent(e)}`;let y=!1;e={cancel:()=>{y=!0}},l.onCancellationRequested(()=>{y=!0});try{let e=await i.sendTo(t,`chatCompletion`,{timeout:15e3,...f?{baseUrl:f}:{},model:p,provider:d,messages:[{role:`system`,content:`You are a code completion engine for ioBroker JavaScript adapter scripts.
2
+ Complete the code at the cursor position marked with <CURSOR>.
3
+ Return ONLY the completion text, no explanation, no markdown fences, no comments about what you did.
4
+ If you cannot complete, return an empty string.
5
+ Available functions: on(), setState(), getState(), schedule(), sendTo(), log(), createState(), setStateDelayed(), existsState(), httpGet(), httpPost(), exec(), formatDate(), $(), wait(), toInt(), toFloat(), readFile(), writeFile().`},{role:`user`,content:`${_}<CURSOR>${v}`}]});if(y||l.isCancellationRequested){c(void 0);return}if(e.error||!e.content){c(void 0);return}let n=e.content.trim(),a=n.match(/```\w*\n?([\s\S]*?)```/);if(a&&(n=a[1].trim()),!n){c(void 0);return}c({items:[{insertText:n,range:new r.Range(s.lineNumber,s.column,s.lineNumber,s.column)}]})}catch{c(void 0)}e=null},800)})}});o.push(c)}return{dispose:()=>{t&&clearTimeout(t),e&&e.cancel(),o.forEach(e=>e.dispose())}}}export{r as registerAiInlineProvider};
@@ -0,0 +1,9 @@
1
+ function e(e){let t=[];for(let n of Object.keys(e)){let r=e[n];if((r==null?void 0:r.type)!==`script`)continue;let i=r.common;if(!(i!=null&&i.source))continue;let a;a=typeof i.name==`object`&&i.name?i.name.en||i.name.de||n:i.name||n,t.push({id:n,name:a,source:i.source,engineType:i.engineType||`Javascript/js`,enabled:i.enabled??!1})}return t}var t=[{regex:e=>RegExp(`getState\\s*\\(\\s*['"\`]${n(e)}['"\`]`,`g`),type:`read`},{regex:e=>RegExp(`setState\\s*\\(\\s*['"\`]${n(e)}['"\`]`,`g`),type:`write`},{regex:e=>RegExp(`setStateChanged\\s*\\(\\s*['"\`]${n(e)}['"\`]`,`g`),type:`write`},{regex:e=>RegExp(`setStateDelayed\\s*\\(\\s*['"\`]${n(e)}['"\`]`,`g`),type:`write`},{regex:e=>RegExp(`on\\s*\\(\\s*['"\`]${n(e)}['"\`]`,`g`),type:`subscribe`},{regex:e=>RegExp(`on\\s*\\(\\s*\\{[^}]*id\\s*:\\s*['"\`]${n(e)}['"\`]`,`g`),type:`subscribe`},{regex:e=>RegExp(`subscribe\\s*\\(\\s*['"\`]${n(e)}['"\`]`,`g`),type:`subscribe`},{regex:e=>RegExp(`existsState\\s*\\(\\s*['"\`]${n(e)}['"\`]`,`g`),type:`exists`},{regex:e=>RegExp(`existsObject\\s*\\(\\s*['"\`]${n(e)}['"\`]`,`g`),type:`exists`},{regex:e=>RegExp(`=\\s*['"\`]${n(e)}['"\`]`,`g`),type:`read`}];function n(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function r(e,n){let r=[];for(let a of e){if(!a.source.includes(n))continue;let e=a.source.split(`
2
+ `);for(let o of t){let t=o.regex(n),s;for(;(s=t.exec(a.source))!==null;){var i;let t=a.source.substring(0,s.index).split(`
3
+ `).length,n=((i=e[t-1])==null?void 0:i.trim())||``;if(!r.some(e=>e.scriptId===a.id&&e.lineNumber===t&&e.usageType===o.type)){let e;e=typeof a.name==`string`?a.name:a.id,r.push({scriptId:a.id,scriptName:e,usageType:o.type,lineNumber:t,line:n})}}}}return r}var i=2e5;function a(e){let t=e.match(/\n\/\/((?:[A-Za-z0-9+/=]){50,})$/);if(t){let n=e.substring(0,e.length-t[0].length).trim();if(n&&!n.startsWith(`<xml`)&&!n.startsWith(`<block`))return n}let n=e.split(`
4
+ `);for(let e=n.length-1;e>=0;e--){let t=n[e].trim();if(t.startsWith(`//`)&&t.length>200&&/^\/\/[A-Za-z0-9+/=%]+$/.test(t)){let t=n.slice(0,e).join(`
5
+ `).trim();if(t&&!t.startsWith(`<xml`)&&!t.startsWith(`<block`))return t}}let r=e.trim();return!r.startsWith(`<xml`)&&!r.startsWith(`<block`)&&!r.startsWith(`<?xml`)?r:null}function o(e){let t=[],n=/<field name="OID">([^<]+)<\/field>/gi,r=new Set,i;for(;(i=n.exec(e))!==null;)r.add(i[1]);r.size>0&&t.push(`Datapoints used: ${[...r].join(`, `)}`);let a=/<field name="(?:VALUE|TEXT|NUM|DELAY_MS|CRON)">([^<]+)<\/field>/gi,o=[],s;for(;(s=a.exec(e))!==null;)s[1].trim()&&o.push(`${s[1].trim()}`);o.length>0&&t.push(`Values/parameters: ${o.join(`, `)}`);let c=/<block type="([^"]+)"/gi,l=new Set,u;for(;(u=c.exec(e))!==null;)l.add(u[1]);let d=[];for(let e of l)(e.includes(`on_ext`)||e.includes(`on_source`))&&d.push(`subscribes to state changes (trigger)`),(e.includes(`set`)||e.includes(`update`))&&d.push(`sets state values`),e.includes(`get`)&&d.push(`reads state values`),(e.includes(`cron`)||e.includes(`schedule`))&&d.push(`uses time schedule/cron`),(e.includes(`telegram`)||e.includes(`sendto`))&&d.push(`sends messages (sendTo)`),(e.includes(`timeout`)||e.includes(`delay`))&&d.push(`uses delays/timeouts`),(e.includes(`log`)||e.includes(`debug`))&&d.push(`logging`),(e.includes(`if`)||e.includes(`logic`)||e.includes(`controls_if`))&&d.push(`conditional logic (if/else)`);d.length>0&&t.push(`Actions: ${[...new Set(d)].join(`, `)}`);let f=/<comment[^>]*>([^<]+)<\/comment>/gi,p=[],m;for(;(m=f.exec(e))!==null;)m[1].trim()&&p.push(m[1].trim());return p.length>0&&t.push(`Comments: ${p.join(`; `)}`),t.length>0?t.join(`
6
+ `):`No details could be extracted from the Blockly XML.`}function s(e,t=!1){if(e.length===0)return`No scripts found.`;let n=[`All scripts in this ioBroker installation:
7
+ `],r=0,s=!1;for(let c of e){let e=c.enabled?`active`:`inactive`,l=c.engineType===`Blockly`||c.engineType===`Rules`,u=c.engineType.includes(`TypeScript`),d=l?`Blockly`:u?`TS`:`JS`,f=`### ${c.id.replace(/^script\.js\./,``).replace(/\./g,`/`)} [${d}, ${e}] (${c.id})`,p;if(l){let e=a(c.source);p=e?`${f}\nThis is a Blockly script. Compiled JavaScript:\n\`\`\`javascript\n${e}\n\`\`\`\n`:`${f}\nThis is a Blockly (visual programming) script. Extracted information:\n${o(c.source)}\n`}else p=`${f}\n${`\`\`\`${u?`typescript`:`javascript`}\n${c.source}\n\`\`\``}\n`;!t&&r+p.length>i?(s=!0,n.push(`${f}\n(source too large to include)\n`)):(n.push(p),r+=p.length)}return s&&n.push(`
8
+ Note: Some script sources were omitted due to size. The user can ask about specific scripts by name.`),n.join(`
9
+ `)}export{e as i,a as n,r,s as t};
@@ -0,0 +1,81 @@
1
+ import{r as e}from"./rolldown-runtime-C0FnF6B9.js";import{$t as t,Hn as n,Nt as r,Un as i,Xn as a,Xt as o,Yt as s,Zt as c,bt as l,f as u,jn as d,o as f,xt as p,yr as m,zt as h}from"./_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__1__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-CxICLr5Z.js";import{n as g,t as _}from"./Import-DpTg1Jow.js";import{t as v}from"./Error-DDfrxAt2.js";import{t as y}from"./blocklyDarkTheme-DEiAX5DT.js";m();var b=window.Blockly,x=class extends Error{constructor(){super(`The field has not yet been attached to its input. Call appendField to attach it.`)}},S=class e extends b.Field{constructor(e,t,n){super(e),d(this,`textGroup`,null),d(this,`borderRect_`,null),d(this,`maxLines_`,1/0),d(this,`isOverflowedY_`,!1),e!==Symbol(`SKIP_SETUP`)&&(n&&this.configure_(n),this.SERIALIZABLE=!0,this.setValue((e==null?void 0:e.toString())||``),t&&this.setValidator(t))}configure_(e){super.configure_(e),e.maxLines&&this.setMaxLines(e.maxLines)}toXml(e){return e.textContent=this.getValue().replace(/\n/g,`&#10;`),e}fromXml(e){this.setValue(e.textContent.replace(/&#10;/g,`
2
+ `))}saveState(){let t=this.saveLegacyState(e);return t===null?this.getValue():t}loadState(e){this.loadLegacyState(b.Field,e)||this.setValue(e)}initView(){this.createBorderRect_(),this.textGroup=b.utils.dom.createSvgElement(b.utils.Svg.G,{class:`blocklyEditableText`},this.fieldGroup_)}onHtmlInputKeyDownSuper_(e){e.key===`Enter`?(b.WidgetDiv.hideIfOwner(this),b.dropDownDiv.hideWithoutAnimation()):e.key===`Escape`?(this.setValue(this.htmlInput_.getAttribute(`data-untyped-default-value`),!1),b.WidgetDiv.hideIfOwner(this),b.dropDownDiv.hideWithoutAnimation()):e.key===`Tab`&&(b.WidgetDiv.hideIfOwner(this),b.dropDownDiv.hideWithoutAnimation(),this.sourceBlock_.tab(this,!e.shiftKey),e.preventDefault())}onHtmlInputChange_(e){let t=this.value_;this.setValue(this.getValueFromEditorText_(this.htmlInput_.value),!1),this.sourceBlock_&&b.Events.isEnabled()&&this.value_!==t&&b.Events.fire(new(b.Events.get(`block_field_intermediate_change`))(this.sourceBlock_,this.name||null,t,this.value_))}onFinishEditing_(e){}getValueFromEditorText_(e){return e}bindInputEvents_(e){this.onKeyDownWrapper_=b.browserEvents.conditionalBind(e,`keydown`,this,this.onHtmlInputKeyDown_),this.onKeyInputWrapper_=b.browserEvents.conditionalBind(e,`input`,this,this.onHtmlInputChange_)}getDisplayText_(){let e=this.getSourceBlock();if(!e)throw Error(`The field has not yet been attached to its input. Call appendField to attach it.`);let t=this.getText();if(!t)return b.Field.NBSP;let n=t.split(`
3
+ `);t=``;let r=this.isOverflowedY_?this.maxLines_:n.length;for(let e=0;e<r;e++){let i=n[e]||``;i.length>this.maxDisplayLength?i=`${i.substring(0,this.maxDisplayLength-4)}...`:this.isOverflowedY_&&e===r-1&&(i=`${i.substring(0,i.length-3)}...`),i=i.replace(/\s/g,b.Field.NBSP),t+=i,e!==r-1&&(t+=`
4
+ `)}return e.RTL&&(t+=`‏`),t}doValueUpdate_(e){super.doValueUpdate_(e),this.value_!==null&&(this.isOverflowedY_=this.value_.split(`
5
+ `).length>this.maxLines_)}render_(){let e=this.getSourceBlock();if(!e)throw Error(`The field has not yet been attached to its input. Call appendField to attach it.`);let t,n=this.textGroup;for(;t=n.firstChild;)n.removeChild(t);let r=this.getConstants();if(!r)throw Error(`Constants not found`);let i=this.getDisplayText_().split(`
6
+ `),a=0;for(let e=0;e<i.length;e++){let t=r.FIELD_TEXT_HEIGHT+r.FIELD_BORDER_RECT_Y_PADDING;b.utils.dom.createSvgElement(b.utils.Svg.TEXT,{class:`blocklyText blocklyMultilineText`,x:r.FIELD_BORDER_RECT_X_PADDING,y:a+r.FIELD_BORDER_RECT_Y_PADDING,dy:r.FIELD_TEXT_BASELINE},n).appendChild(document.createTextNode(i[e])),a+=t}if(this.isBeingEdited_){let e=this.htmlInput_;this.isOverflowedY_?b.utils.dom.addClass(e,`blocklyHtmlTextAreaInputOverflowedY`):b.utils.dom.removeClass(e,`blocklyHtmlTextAreaInputOverflowedY`)}if(this.updateSize_(),this.isBeingEdited_){e.RTL?setTimeout(this.resizeEditor_.bind(this),0):this.resizeEditor_();let t=this.htmlInput_;this.isTextValid_?(b.utils.dom.removeClass(t,`blocklyInvalidInput`),b.utils.aria.setState(t,b.utils.aria.State.INVALID,!1)):(b.utils.dom.addClass(t,`blocklyInvalidInput`),b.utils.aria.setState(t,b.utils.aria.State.INVALID,!0))}}updateSize_(){let e=this.getConstants();if(!e)throw Error(`Constants not found`);let t=this.textGroup.childNodes,n=e.FIELD_TEXT_FONTSIZE,r=e.FIELD_TEXT_FONTWEIGHT,i=e.FIELD_TEXT_FONTFAMILY,a=0,o=0;for(let s=0;s<t.length;s++){let c=t[s],l=b.utils.dom.getFastTextWidth(c,n,r,i);l>a&&(a=l),o+=e.FIELD_TEXT_HEIGHT+(s>0?e.FIELD_BORDER_RECT_Y_PADDING:0)}if(this.isBeingEdited_){let e=String(this.value_).split(`
7
+ `),t=b.utils.dom.createSvgElement(b.utils.Svg.TEXT,{class:`blocklyText blocklyMultilineText`});for(let o=0;o<e.length;o++){e[o].length>this.maxDisplayLength&&(e[o]=e[o].substring(0,this.maxDisplayLength)),t.textContent=e[o];let s=b.utils.dom.getFastTextWidth(t,n,r,i);s>a&&(a=s)}let o=this.htmlInput_,s=o.offsetWidth-o.clientWidth;a+=s}this.borderRect_&&(o+=e.FIELD_BORDER_RECT_Y_PADDING*2,a+=e.FIELD_BORDER_RECT_X_PADDING*2+1,this.borderRect_.setAttribute(`width`,`${a}`),this.borderRect_.setAttribute(`height`,`${o}`)),this.size_.width=a,this.size_.height=o,this.positionBorderRect_()}showInlineEditor_(e){let t=this.getSourceBlock();if(!t)throw new x;b.WidgetDiv.show(this,t.RTL,this.widgetDispose_.bind(this),this.workspace_),this.htmlInput_=this.widgetCreate_(),this.isBeingEdited_=!0,this.valueWhenEditorWasOpened_=this.value_,e||(this.htmlInput_.focus({preventScroll:!0}),this.htmlInput_.select())}getEditorText_(e){return`${e}`}getScaledBBox(){let e,t,n,r=this.getSourceBlock();if(!r)throw new x;if(this.isFullBlockField()){let i=this.sourceBlock_.getHeightWidth(),a=r.workspace.scale;n=this.getAbsoluteXY_(),e=(i.width+1)*a,t=(i.height+1)*a,b.utils.userAgent.GECKO?(n.x+=1.5*a,n.y+=1.5*a):(n.x-=.5*a,n.y-=.5*a)}else{let r=this.borderRect_.getBoundingClientRect();n=b.utils.style.getPageOffset(this.borderRect_),e=r.width,t=r.height}return new b.utils.Rect(n.y,n.y+t,n.x,n.x+e)}resizeEditor_(){b.renderManagement.finishQueuedRenders().then(()=>{let e=this.getSourceBlock();if(!e)throw new x;let t=b.WidgetDiv.getDiv(),n=this.getScaledBBox();t.style.width=`${n.right-n.left}px`,t.style.height=`${n.bottom-n.top}px`;let r=e.RTL?n.right-t.offsetWidth:n.left,i=n.top;t.style.left=`${r}px`,t.style.top=`${i}px`})}unbindInputEvents_(){this.onKeyDownWrapper_&&=(b.browserEvents.unbind(this.onKeyDownWrapper_),null),this.onKeyInputWrapper_&&=(b.browserEvents.unbind(this.onKeyInputWrapper_),null)}getClickTarget_(){return this.clickTarget_||this.getSvgRoot()}widgetDispose_(){this.isBeingEdited_=!1,this.isTextValid_=!0,this.forceRerender(),this.onFinishEditing_(this.value_),this.sourceBlock_&&b.Events.isEnabled()&&this.valueWhenEditorWasOpened_!==null&&this.valueWhenEditorWasOpened_!==this.value_&&(b.Events.fire(new(b.Events.get(`change`))(this.sourceBlock_,`field`,this.name||null,this.valueWhenEditorWasOpened_,this.value_)),this.valueWhenEditorWasOpened_=null),b.Events.setGroup(!1),this.unbindInputEvents_();let e=b.WidgetDiv.getDiv().style;e.width=`auto`,e.height=`auto`,e.fontSize=``,e.transition=``,e.boxShadow=``,this.htmlInput_=null;let t=this.getClickTarget_();if(!t)throw Error(`A click target has not been set.`);b.utils.dom.removeClass(t,`editing`)}showEditor_(e,t){this.workspace_=this.sourceBlock_.workspace,!t&&this.workspace_.options.modalInputs&&(b.utils.userAgent.MOBILE||b.utils.userAgent.ANDROID||b.utils.userAgent.IPAD)?this.showPromptEditor_():this.showInlineEditor_(!!t),this.forceRerender()}widgetCreate_(){let e=b.WidgetDiv.getDiv(),t=this.workspace_.getScale(),n=this.getConstants();if(!n)throw Error(`Constants not found`);let r=document.createElement(`textarea`);r.className=`blocklyHtmlInput blocklyHtmlTextAreaInput`,r.setAttribute(`spellcheck`,String(this.spellcheck_));let i=`${n.FIELD_TEXT_FONTSIZE*t}pt`;e.style.fontSize=i,r.style.fontSize=i;let a=`${b.FieldTextInput.BORDERRADIUS*t}px`;r.style.borderRadius=a;let o=n.FIELD_BORDER_RECT_X_PADDING*t,s=n.FIELD_BORDER_RECT_Y_PADDING*t/2;r.style.padding=`${s}px ${o}px ${s}px ${o}px`;let c=n.FIELD_TEXT_HEIGHT+n.FIELD_BORDER_RECT_Y_PADDING;return r.style.lineHeight=`${c*t}px`,e.appendChild(r),r.value=r.defaultValue=this.getEditorText_(this.value_),r.setAttribute(`data-untyped-default-value`,String(this.value_)),r.setAttribute(`data-old-value`,``),b.utils.userAgent.GECKO?setTimeout(this.resizeEditor_.bind(this),0):this.resizeEditor_(),this.bindInputEvents_(r),r}setMaxLines(e){typeof e==`number`&&e>0&&e!==this.maxLines_&&(this.maxLines_=e,this.forceRerender())}getMaxLines(){return this.maxLines_}onHtmlInputKeyDown_(e){e.key!==`Enter`&&this.onHtmlInputKeyDownSuper_(e)}static fromJson(e){let t=b.utils.parsing.replaceMessageReferences(e.text);return new this(t,void 0,e)}};b.Css.register(`
8
+ .blocklyHtmlTextAreaInput {
9
+ font-family: monospace;
10
+ resize: none;
11
+ overflow: hidden;
12
+ height: 100%;
13
+ text-align: left;
14
+ }
15
+
16
+ .blocklyHtmlTextAreaInputOverflowedY {
17
+ overflow-y: scroll;
18
+ }
19
+ `);var C=`text_multiline`,w={type:C,message0:`%1 %2`,args0:[{type:`field_image`,src:`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAARCAYAAADpPU2iAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAdhgAAHYYBXaITgQAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMS42/U4J6AAAAP1JREFUOE+Vks0KQUEYhjmRIja4ABtZ2dm5A3t3Ia6AUm7CylYuQRaUhZSlLZJiQbFAyRnPN33y01HOW08z8873zpwzM4F3GWOCruvGIE4/rLaV+Nq1hVGMBqzhqlxgCys4wJA65xnogMHsQ5lujnYHTejBBCK2mE4abjCgMGhNxHgDFWjDSG07kdfVa2pZMf4ZyMAdWmpZMfYOsLiDMYMjlMB+K613QISRhTnITnsYg5yUd0DETmEoMlkFOeIT/A58iyK5E18BuTBfgYXfwNJv4P9/oEBerLylOnRhygmGdPpTTBZAPkde61lbQe4moWUvYUZYLfUNftIY4zwA5X2Z9AYnQrEAAAAASUVORK5CYII=`,width:12,height:17,alt:`¶`},{type:`field_multilinetext`,name:`TEXT`,text:``}],output:`String`,style:`text_blocks`,helpUrl:`%{BKY_TEXT_TEXT_HELPURL}`,tooltip:`%{BKY_TEXT_TEXT_TOOLTIP}`,extensions:[`parent_tooltip_when_inline`]};function T(e,t){let n=t.multiline_quote_(e.getFieldValue(`TEXT`));return[n,n.indexOf(`+`)===-1?0:6.2]}window.Blockly.common.createBlockDefinitionsFromJsonArray([w])[C];var E=window.Blockly,D=class extends E.Field{constructor(e,t,n){super(e),d(this,`picker`,null),d(this,`highlightedIndex`,null),d(this,`boundEvents`,[]),d(this,`SERIALIZABLE`,!0),d(this,`CURSOR`,`default`),d(this,`isDirty_`,!1),d(this,`colours`,`#ffffff.#cccccc.#c0c0c0.#999999.#666666.#333333.#000000.#ffcccc.#ff6666.#ff0000.#cc0000.#990000.#660000.#330000.#ffcc99.#ff9966.#ff9900.#ff6600.#cc6600.#993300.#663300.#ffff99.#ffff66.#ffcc66.#ffcc33.#cc9933.#996633.#663333.#ffffcc.#ffff33.#ffff00.#ffcc00.#999900.#666600.#333300.#99ff99.#66ff99.#33ff33.#33cc00.#009900.#006600.#003300.#99ffff.#33ffff.#66cccc.#00cccc.#339999.#336666.#003333.#ccffff.#66ffff.#33ccff.#3366ff.#3333ff.#000099.#000066.#ccccff.#9999ff.#6666cc.#6633ff.#6600cc.#333399.#330099.#ffccff.#ff99ff.#cc66cc.#cc33cc.#993399.#663366.#330033`.split(`.`)),d(this,`titles`,[]),d(this,`columns`,7),e!==Symbol(`SKIP_SETUP`)&&(n&&this.configure_(n),this.setValue(e),t&&this.setValidator(t))}configure_(e){super.configure_(e),e.colourOptions&&(this.colours=e.colourOptions),e.colourTitles&&(this.titles=e.colourTitles),e.columns&&(this.columns=e.columns)}initView(){let e=this.getConstants();if(!e)throw Error(`Constants not found`);this.size_=new E.utils.Size(e.FIELD_COLOUR_DEFAULT_WIDTH,e.FIELD_COLOUR_DEFAULT_HEIGHT),this.createBorderRect_(),this.getBorderRect().style.fillOpacity=`1`,this.getBorderRect().setAttribute(`stroke`,`#fff`),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}isFullBlockField(){if(!this.getSourceBlock())throw new E.UnattachedFieldError;let e=this.getConstants();return this.blockIsSimpleReporter()&&!!(e!=null&&e.FIELD_COLOUR_FULL_BLOCK)}blockIsSimpleReporter(){let e=this.getSourceBlock();if(!e)throw new E.UnattachedFieldError;if(!e.outputConnection)return!1;for(let t of e.inputList)if(t.connection||t.fieldRow.length>1)return!1;return!0}applyColour(){let e=this.getSourceBlock();if(!e)throw new E.UnattachedFieldError;if(!this.fieldGroup_)return;let t=this.borderRect_;if(!t)throw Error(`The border rect has not been initialized`);this.isFullBlockField()?(t.style.display=`none`,e.pathObject.svgPath.setAttribute(`fill`,this.getValue()),e.pathObject.svgPath.setAttribute(`stroke`,`#fff`)):(t.style.display=`block`,t.style.fill=this.getValue())}getSize(){var e;return(e=this.getConstants())!=null&&e.FIELD_COLOUR_FULL_BLOCK&&(this.render_(),this.isDirty_=!1),super.getSize()}render_(){super.render_();let e=this.getSourceBlock();if(!e)throw new E.UnattachedFieldError;e.applyColour()}updateSize_(e){let t=this.getConstants();if(!t)return;let n,r;this.isFullBlockField()?(n=(e??0)*2,r=t.FIELD_TEXT_HEIGHT):(n=t.FIELD_COLOUR_DEFAULT_WIDTH,r=t.FIELD_COLOUR_DEFAULT_HEIGHT),this.size_.height=r,this.size_.width=n,this.positionBorderRect_()}doClassValidation_(e){return typeof e==`string`?E.utils.colour.parse(e):null}getText(){let e=this.value_;return/^#(.)\1(.)\2(.)\3$/.test(e)&&(e=`#${e[1]}${e[3]}${e[5]}`),e}setColours(e,t){return this.colours=e,t&&(this.titles=t),this}setColumns(e){return this.columns=e,this}showEditor_(){if(this.dropdownCreate(),!this.picker)throw Error(`Picker not found`);E.DropDownDiv.getContentDiv().appendChild(this.picker),E.DropDownDiv.showPositionedByField(this,this.dropdownDispose.bind(this)),this.picker.focus({preventScroll:!0})}onClick(e){let t=e.target,n=t==null?void 0:t.getAttribute(`data-colour`);n!==null&&(this.setValue(n),E.DropDownDiv.hideIfOwner(this))}onKeyDown(e){let t=!0,n;switch(e.key){case`ArrowUp`:this.moveHighlightBy(0,-1);break;case`ArrowDown`:this.moveHighlightBy(0,1);break;case`ArrowLeft`:this.moveHighlightBy(-1,0);break;case`ArrowRight`:this.moveHighlightBy(1,0);break;case`Enter`:if(n=this.getHighlighted(),n){let e=n.getAttribute(`data-colour`);e!==null&&this.setValue(e)}E.DropDownDiv.hideWithoutAnimation();break;default:t=!1}t&&e.stopPropagation()}moveHighlightBy(e,t){if(!this.highlightedIndex)return;let n=this.colours,r=this.columns,i=this.highlightedIndex%r,a=Math.floor(this.highlightedIndex/r);i+=e,a+=t,e<0?i<0&&a>0?(i=r-1,a--):i<0&&(i=0):e>0?i>r-1&&a<Math.floor(n.length/r)-1?(i=0,a++):i>r-1&&i--:t<0?a<0&&(a=0):t>0&&a>Math.floor(n.length/r)-1&&(a=Math.floor(n.length/r)-1);let o=this.picker.childNodes[a].childNodes[i],s=a*r+i;this.setHighlightedCell(o,s)}onMouseMove(e){let t=e.target,n=t&&Number(t.getAttribute(`data-index`));n!==null&&n!==this.highlightedIndex&&this.setHighlightedCell(t,n)}onMouseEnter(){var e;(e=this.picker)==null||e.focus({preventScroll:!0})}onMouseLeave(){var e;(e=this.picker)==null||e.blur();let t=this.getHighlighted();t&&E.utils.dom.removeClass(t,`blocklyColourHighlighted`)}getHighlighted(){var e;if(!this.highlightedIndex)return null;let t=this.highlightedIndex%this.columns,n=Math.floor(this.highlightedIndex/this.columns),r=(e=this.picker)==null?void 0:e.childNodes[n];return r?r.childNodes[t]:null}setHighlightedCell(e,t){let n=this.getHighlighted();n&&E.utils.dom.removeClass(n,`blocklyColourHighlighted`),E.utils.dom.addClass(e,`blocklyColourHighlighted`),this.highlightedIndex=t;let r=e.getAttribute(`id`);r&&this.picker&&E.utils.aria.setState(this.picker,E.utils.aria.State.ACTIVEDESCENDANT,r)}dropdownCreate(){let e=this.columns,t=this.colours,n=this.getValue(),r=document.createElement(`table`);r.className=`blocklyColourTable`,r.tabIndex=0,r.dir=`ltr`,E.utils.aria.setRole(r,E.utils.aria.Role.GRID),E.utils.aria.setState(r,E.utils.aria.State.EXPANDED,!0),E.utils.aria.setState(r,E.utils.aria.State.ROWCOUNT,Math.floor(t.length/e)),E.utils.aria.setState(r,E.utils.aria.State.COLCOUNT,e);let i=null;for(let a=0;a<t.length;a++){a%e===0&&(i=document.createElement(`tr`),E.utils.aria.setRole(i,E.utils.aria.Role.ROW),r.appendChild(i));let o=document.createElement(`td`);i.appendChild(o),o.setAttribute(`data-colour`,t[a]),o.title=this.titles[a]||t[a],o.id=E.utils.idGenerator.getNextUniqueId(),o.setAttribute(`data-index`,`${a}`),E.utils.aria.setRole(o,E.utils.aria.Role.GRIDCELL),E.utils.aria.setState(o,E.utils.aria.State.LABEL,t[a]),E.utils.aria.setState(o,E.utils.aria.State.SELECTED,t[a]===n),o.style.backgroundColor=t[a],t[a]===n&&(o.className=`blocklyColourSelected`,this.highlightedIndex=a)}this.boundEvents.push(E.browserEvents.conditionalBind(r,`pointerdown`,this,this.onClick,!0)),this.boundEvents.push(E.browserEvents.conditionalBind(r,`pointermove`,this,this.onMouseMove,!0)),this.boundEvents.push(E.browserEvents.conditionalBind(r,`pointerenter`,this,this.onMouseEnter,!0)),this.boundEvents.push(E.browserEvents.conditionalBind(r,`pointerleave`,this,this.onMouseLeave,!0)),this.boundEvents.push(E.browserEvents.conditionalBind(r,`keydown`,this,this.onKeyDown,!1)),this.picker=r}dropdownDispose(){for(let e of this.boundEvents)E.browserEvents.unbind(e);this.boundEvents.length=0,this.picker=null,this.highlightedIndex=null}static fromJson(e){return new this(e.colour,void 0,e)}};D.prototype.DEFAULT_VALUE=`#ffffff`,E.Css.register(`
20
+ .blocklyColourTable {
21
+ border-collapse: collapse;
22
+ display: block;
23
+ outline: none;
24
+ padding: 1px;
25
+ }
26
+
27
+ .blocklyColourTable>tr>td {
28
+ border: 0.5px solid #888;
29
+ box-sizing: border-box;
30
+ cursor: pointer;
31
+ display: inline-block;
32
+ height: 20px;
33
+ padding: 0;
34
+ width: 20px;
35
+ }
36
+
37
+ .blocklyColourTable>tr>td.blocklyColourHighlighted {
38
+ border-color: #eee;
39
+ box-shadow: 2px 2px 7px 2px rgba(0, 0, 0, 0.3);
40
+ position: relative;
41
+ }
42
+
43
+ .blocklyColourSelected, .blocklyColourSelected:hover {
44
+ border-color: #eee !important;
45
+ outline: 1px solid #333;
46
+ position: relative;
47
+ }
48
+ `);var O=`colour_picker`,k={type:O,message0:`%1`,args0:[{type:`field_colour`,name:`COLOUR`,colour:`#ff0000`}],output:`Colour`,helpUrl:`%{BKY_COLOUR_PICKER_HELPURL}`,style:`colour_blocks`,tooltip:`%{BKY_COLOUR_PICKER_TOOLTIP}`,extensions:[`parent_tooltip_when_inline`]};function A(e,t){return[t.quote_(e.getFieldValue(`COLOUR`)),0]}window.Blockly.common.createBlockDefinitionsFromJsonArray([k])[O];var j=`colour_random`,M={type:j,message0:`%{BKY_COLOUR_RANDOM_TITLE}`,output:`Colour`,helpUrl:`%{BKY_COLOUR_RANDOM_HELPURL}`,style:`colour_blocks`,tooltip:`%{BKY_COLOUR_RANDOM_TOOLTIP}`};function N(e,t){return[`${t.provideFunction_(`colourRandom`,`
49
+ function ${t.FUNCTION_NAME_PLACEHOLDER_}() {
50
+ var num = Math.floor(Math.random() * 0x1000000);
51
+ return '#' + ('00000' + num.toString(16)).substr(-6);
52
+ }
53
+ `)}()`,2]}window.Blockly.common.createBlockDefinitionsFromJsonArray([M])[j];var P=`colour_rgb`,F={type:P,message0:`%{BKY_COLOUR_RGB_TITLE} %{BKY_COLOUR_RGB_RED} %1 %{BKY_COLOUR_RGB_GREEN} %2 %{BKY_COLOUR_RGB_BLUE} %3`,args0:[{type:`input_value`,name:`RED`,check:`Number`,align:`RIGHT`},{type:`input_value`,name:`GREEN`,check:`Number`,align:`RIGHT`},{type:`input_value`,name:`BLUE`,check:`Number`,align:`RIGHT`}],output:`Colour`,helpUrl:`%{BKY_COLOUR_RGB_HELPURL}`,style:`colour_blocks`,tooltip:`%{BKY_COLOUR_RGB_TOOLTIP}`};function I(e,t){let n=t.valueToCode(e,`RED`,99)||0,r=t.valueToCode(e,`GREEN`,99)||0,i=t.valueToCode(e,`BLUE`,99)||0;return[`${t.provideFunction_(`colourRgb`,`
54
+ function ${t.FUNCTION_NAME_PLACEHOLDER_}(r, g, b) {
55
+ r = Math.max(Math.min(Number(r), 100), 0) * 2.55;
56
+ g = Math.max(Math.min(Number(g), 100), 0) * 2.55;
57
+ b = Math.max(Math.min(Number(b), 100), 0) * 2.55;
58
+ r = ('0' + (Math.round(r) || 0).toString(16)).slice(-2);
59
+ g = ('0' + (Math.round(g) || 0).toString(16)).slice(-2);
60
+ b = ('0' + (Math.round(b) || 0).toString(16)).slice(-2);
61
+ return '#' + r + g + b;
62
+ }
63
+ `)}(${n}, ${r}, ${i})`,2]}window.Blockly.common.createBlockDefinitionsFromJsonArray([F])[P];var L=`colour_blend`,R={type:L,message0:`%{BKY_COLOUR_BLEND_TITLE} %{BKY_COLOUR_BLEND_COLOUR1} %1 %{BKY_COLOUR_BLEND_COLOUR2} %2 %{BKY_COLOUR_BLEND_RATIO} %3`,args0:[{type:`input_value`,name:`COLOUR1`,check:`Colour`,align:`RIGHT`},{type:`input_value`,name:`COLOUR2`,check:`Colour`,align:`RIGHT`},{type:`input_value`,name:`RATIO`,check:`Number`,align:`RIGHT`}],output:`Colour`,helpUrl:`%{BKY_COLOUR_BLEND_HELPURL}`,style:`colour_blocks`,tooltip:`%{BKY_COLOUR_BLEND_TOOLTIP}`};function z(e,t){let n=t.valueToCode(e,`COLOUR1`,99)||`'#000000'`,r=t.valueToCode(e,`COLOUR2`,99)||`'#000000'`,i=t.valueToCode(e,`RATIO`,99)||.5;return[`${t.provideFunction_(`colourBlend`,`
64
+ function ${t.FUNCTION_NAME_PLACEHOLDER_}(c1, c2, ratio) {
65
+ ratio = Math.max(Math.min(Number(ratio), 1), 0);
66
+ var r1 = parseInt(c1.substring(1, 3), 16);
67
+ var g1 = parseInt(c1.substring(3, 5), 16);
68
+ var b1 = parseInt(c1.substring(5, 7), 16);
69
+ var r2 = parseInt(c2.substring(1, 3), 16);
70
+ var g2 = parseInt(c2.substring(3, 5), 16);
71
+ var b2 = parseInt(c2.substring(5, 7), 16);
72
+ var r = Math.round(r1 * (1 - ratio) + r2 * ratio);
73
+ var g = Math.round(g1 * (1 - ratio) + g2 * ratio);
74
+ var b = Math.round(b1 * (1 - ratio) + b2 * ratio);
75
+ r = ('0' + (r || 0).toString(16)).slice(-2);
76
+ g = ('0' + (g || 0).toString(16)).slice(-2);
77
+ b = ('0' + (b || 0).toString(16)).slice(-2);
78
+ return '#' + r + g + b;
79
+ }
80
+ `)}(${n}, ${r}, ${i})`,2]}window.Blockly.common.createBlockDefinitionsFromJsonArray([R])[L];function B(){window.Blockly.FieldMultilineInput||(window.Blockly.fieldRegistry.register(`field_multilinetext`,S),window.Blockly.JavaScript.forBlock.text_multiline=T,window.Blockly.FieldMultilineInput=S,Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:`text_multiline`,message0:`%1 %2`,args0:[{type:`field_image`,src:`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAARCAYAAADpPU2iAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAdhgAAHYYBXaITgQAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMS42/U4J6AAAAP1JREFUOE+Vks0KQUEYhjmRIja4ABtZ2dm5A3t3Ia6AUm7CylYuQRaUhZSlLZJiQbFAyRnPN33y01HOW08z8873zpwzM4F3GWOCruvGIE4/rLaV+Nq1hVGMBqzhqlxgCys4wJA65xnogMHsQ5lujnYHTejBBCK2mE4abjCgMGhNxHgDFWjDSG07kdfVa2pZMf4ZyMAdWmpZMfYOsLiDMYMjlMB+K613QISRhTnITnsYg5yUd0DETmEoMlkFOeIT/A58iyK5E18BuTBfgYXfwNJv4P9/oEBerLylOnRhygmGdPpTTBZAPkde61lbQe4moWUvYUZYLfUNftIY4zwA5X2Z9AYnQrEAAAAASUVORK5CYII=`,width:12,height:17,alt:`¶`},{type:`field_multilinetext`,name:`TEXT`,text:``}],output:`String`,style:`text_blocks`,helpUrl:`%{BKY_TEXT_TEXT_HELPURL}`,tooltip:`%{BKY_TEXT_TEXT_TOOLTIP}`,extensions:[`parent_tooltip_when_inline`]}]))),window.Blockly.FieldColour||(window.Blockly.fieldRegistry.register(`field_colour`,D),window.Blockly.JavaScript.forBlock.colour_picker=A,window.Blockly.JavaScript.forBlock.colour_blend=z,window.Blockly.JavaScript.forBlock.colour_random=N,window.Blockly.JavaScript.forBlock.colour_rgb=I,window.Blockly.FieldColour=D,Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:`colour_picker`,message0:`%1`,args0:[{type:`field_colour`,name:`COLOUR`,colour:`#ff0000`}],output:`Colour`,helpUrl:`%{BKY_COLOUR_PICKER_HELPURL}`,style:`colour_blocks`,tooltip:`%{BKY_COLOUR_PICKER_TOOLTIP}`,extensions:[`parent_tooltip_when_inline`]}])),Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:`colour_random`,message0:`%{BKY_COLOUR_RANDOM_TITLE}`,output:`Colour`,helpUrl:`%{BKY_COLOUR_RANDOM_HELPURL}`,style:`colour_blocks`,tooltip:`%{BKY_COLOUR_RANDOM_TOOLTIP}`}])),Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:`colour_rgb`,message0:`%{BKY_COLOUR_RGB_TITLE} %{BKY_COLOUR_RGB_RED} %1 %{BKY_COLOUR_RGB_GREEN} %2 %{BKY_COLOUR_RGB_BLUE} %3`,args0:[{type:`input_value`,name:`RED`,check:`Number`,align:`RIGHT`},{type:`input_value`,name:`GREEN`,check:`Number`,align:`RIGHT`},{type:`input_value`,name:`BLUE`,check:`Number`,align:`RIGHT`}],output:`Colour`,helpUrl:`%{BKY_COLOUR_RGB_HELPURL}`,style:`colour_blocks`,tooltip:`%{BKY_COLOUR_RGB_TOOLTIP}`}])),Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:`colour_blend`,message0:`%{BKY_COLOUR_BLEND_TITLE} %{BKY_COLOUR_BLEND_COLOUR1} %1 %{BKY_COLOUR_BLEND_COLOUR2} %2 %{BKY_COLOUR_BLEND_RATIO} %3`,args0:[{type:`input_value`,name:`COLOUR1`,check:`Colour`,align:`RIGHT`},{type:`input_value`,name:`COLOUR2`,check:`Colour`,align:`RIGHT`},{type:`input_value`,name:`RATIO`,check:`Number`,align:`RIGHT`}],output:`Colour`,helpUrl:`%{BKY_COLOUR_BLEND_HELPURL}`,style:`colour_blocks`,tooltip:`%{BKY_COLOUR_BLEND_TOOLTIP}`}])));let e=window.Blockly.JavaScript;e.forBlock&&Object.keys(e).forEach(t=>{typeof e[t]==`function`&&(e.forBlock[t]||(console.log(`Migrating Blockly.JavaScript.${t} to Blockly.JavaScript.forBlock.${t}`),e.forBlock[t]=e[t],delete e[t]))})}var V=e({default:()=>J}),H=!1,U=!1,W=null,G=null,K=[];function q(e,t,n,r){if(r||=[],(e.tagName===`BLOCK`||e.tagName===`block`)&&(n=e.id),e.tagName===`FIELD`||e.tagName===`field`)for(let a=0;a<e.attributes.length;a++){let o=(e.attributes[a].value||``).toLowerCase();if(e.attributes[a].nodeName===`name`&&(o===`oid`||o===`text`||o===`var`)){var i;n&&(i=e.innerHTML)!=null&&i.toLowerCase().includes(t)&&r.push(n)}}return e.childNodes.forEach(e=>q(e,t,n,r)),r}var J=class e extends a.Component{constructor(t){super(t),d(this,`blockly`,null),d(this,`blocklyWorkspace`,null),d(this,`originalCode`,void 0),d(this,`someSelected`,null),d(this,`changeTimer`,null),d(this,`someSelectedTime`,0),d(this,`ignoreChanges`,!1),d(this,`blinkBlock`,void 0),d(this,`onResizeBind`,void 0),d(this,`resizeObserver`,null),d(this,`didUpdate`,null),d(this,`lastCommand`,``),d(this,`lastSearch`,void 0),d(this,`onShowNameDialog`,(e,t,n)=>{this.setState({showInputPrompt:{promptText:e,defaultText:t,callback:n,value:t}})}),this.state={languageOwnLoaded:U,languageBlocklyLoaded:H,changed:!1,message:``,error:``,themeType:this.props.themeType,exportText:``,importText:!1,searchText:this.props.searchText||``,showInputPrompt:null},this.originalCode=t.code||``,this.someSelected=null,this.onResizeBind=this.onResize.bind(this),this.lastSearch=this.props.searchText||``,this.blinkBlock=null,B(),e.Blockly.dialog.setPrompt(this.onShowNameDialog),this.loadLanguages()}static loadJS(e,t,n){let r=document.createElement(`script`);try{r.src=e,r.onload=t,r.onerror=t,(n||window.document.body).appendChild(r)}catch(n){console.error(`Cannot load ${e}: ${n}`),t&&t()}}static loadScripts(t,n){if(!(t!=null&&t.length)){n&&n();return}let r=t.pop();r&&!K.includes(r)?(K.push(r),e.loadJS(`../../adapter/${r}/blockly.js`,()=>setTimeout(()=>e.loadScripts(t,n),0))):setTimeout(()=>e.loadScripts(t,n),0)}static loadCustomBlockly(t,n){let r=[];for(let e in t){var i;!Object.prototype.hasOwnProperty.call(t,e)||!t[e]||!e.match(/^system\.adapter\./)||t[e].type!==`adapter`||(i=t[e].common)!=null&&i.blockly&&(console.log(`Detected custom blockly: ${t[e].common.name}`),r.push(t[e].common.name))}e.loadScripts(r,n)}static loadXMLDoc(e){let t;return t=window.DOMParser?e=>new window.DOMParser().parseFromString(e,`text/xml`):window.ActiveXObject!==void 0&&new window.ActiveXObject(`Microsoft.XMLDOM`)?e=>{let t=new window.ActiveXObject(`Microsoft.XMLDOM`);return t.async=`false`,t.loadXML(e),t}:()=>null,t(e)}searchBlocks(t){if(this.blocklyWorkspace){let n=q(e.Blockly.Xml.workspaceToDom(this.blocklyWorkspace),t.toLowerCase());return console.log(`Search "${t}" found blocks: ${n.length?JSON.stringify(n):`none`}`),n}return[]}searchId(){let e=this.lastSearch?this.searchBlocks(this.lastSearch):null;e!=null&&e.length?(this.someSelected=e,this.someSelected.forEach(e=>{var t;return(t=this.blocklyWorkspace)==null?void 0:t.highlightBlock(e,!0)}),this.someSelectedTime=Date.now()):this.someSelected&&=(this.someSelected.forEach(e=>{var t;return(t=this.blocklyWorkspace)==null?void 0:t.highlightBlock(e,!1)}),null)}UNSAFE_componentWillReceiveProps(t){t.command&&this.lastCommand!==t.command&&(this.lastCommand=t.command,setTimeout(()=>this.lastCommand=``,300),this.lastCommand===`check`?this.blocklyCheckBlocks((t,n)=>{t?(n&&e.blocklyBlinkBlock(n),this.setState({error:{text:u.t(t),title:u.t(`Error was found`)}}),this.blinkBlock=n):this.setState({message:u.t(`Ok`)})}):this.lastCommand===`export`?this.exportBlocks():this.lastCommand===`import`&&this.importBlocks()),t.searchText!==this.lastSearch&&(this.lastSearch=t.searchText,this.searchId()),this.state.themeType!==t.themeType&&this.setState({themeType:t.themeType},()=>this.updateBackground()),this.originalCode!==t.code&&(this.originalCode=t.code||``,this.loadCode(),this.searchId())}loadLanguages(){if(!H){let e=window.document.createElement(`script`);e.setAttribute(`type`,`text/javascript`),e.setAttribute(`src`,`google-blockly/msg/js/${u.getLanguage()}.js`),e.onload=()=>{H=!0,this.setState({languageBlocklyLoaded:H})},window.document.getElementsByTagName(`head`)[0].appendChild(e)}if(!U){let e=window.document.createElement(`script`);e.setAttribute(`type`,`text/javascript`),e.setAttribute(`src`,`google-blockly/own/msg/${u.getLanguage()}.js`),e.onload=()=>{U=!0,this.setState({languageOwnLoaded:U})},window.document.getElementsByTagName(`head`)[0].appendChild(e)}}onResize(){this.blocklyWorkspace&&e.Blockly.svgResize(this.blocklyWorkspace)}static jsCode2Blockly(e){e||=``;let t=e.split(/[\r\n]+|\r|\n/g),n=``;for(let e=t.length-1;e>=0;e--)if(t[e].substring(0,2)===`//`){n=t[e].substring(2);break}if(n.substring(0,4)===`<xml`)return n;let r;try{r=window.decodeURIComponent(window.atob(n))}catch(e){r=null,console.error(`cannot decode: ${n}`),console.error(e)}return r}static blocklyBlinkBlock(e){for(let t=300;t<3e3;t+=300)setTimeout(()=>e.select(),t),setTimeout(()=>e.unselect(),t+150)}blocklyRemoveOrphanedShadows(){if(this.blocklyWorkspace){let e=this.blocklyWorkspace.getAllBlocks(),t;for(let n=0;t=e[n];n++)if(t.isShadow()){let e=t.getConnections_(!0),n;for(let r=0;n=e[r];r++)if(!n.targetConnection){t.dispose();break}}}}blocklyCheckBlocks(t){let n;if(!this.blocklyWorkspace||this.blocklyWorkspace.getAllBlocks().length===0)return t&&t(`no blocks found`),!1;let r=this.blocklyGetUnconnectedBlock();return r?n=`not properly connected`:(r=this.blocklyGetBlockWithWarning(),r&&(n=`warning on this block`)),r?(t?t(n,r):e.blocklyBlinkBlock(r),!1):(t(),!0)}blocklyGetUnconnectedBlock(){var t;let n=(t=this.blocklyWorkspace)==null?void 0:t.getAllBlocks(),r;if(n)for(let t=0;r=n[t];t++){let t=r.getConnections_(!0),n;for(let i=0;n=t[i];i++)if(!n.sourceBlock_||(n.type===e.Blockly.INPUT_VALUE||n.type===e.Blockly.OUTPUT_VALUE)&&!n.targetConnection&&!n._optional)return r}return null}blocklyGetBlockWithWarning(){var e;let t=(e=this.blocklyWorkspace)==null?void 0:e.getAllBlocks(),n;if(t){for(let e=0;n=t[e];e++)if(n.warning)return n}return null}appendBlocksFromXml(e){this.onImportBlocks(e)}applyAiBlocks(t){if(this.blocklyWorkspace&&(t=(t||``).trim(),t))try{t.startsWith(`<xml`)||(t=`<xml xmlns="https://developers.google.com/blockly/xml">${t}</xml>`),t=t.replace(/[\n\r]/g,``).replace(/<variables>.*<\/variables>/g,``);let n=e.Blockly.utils.xml.textToDom(t),r=Array.from(n.querySelectorAll(`:scope > block`));if(r.length===0)return;let i=e=>{let t=e.getAttribute(`type`)||``,n=[];for(let t of Array.from(e.children))t.tagName===`field`&&n.push(`${t.getAttribute(`name`)}=${t.textContent}`),t.tagName===`mutation`&&n.push(`mut:${t.outerHTML}`);return`${t}|${n.join(`,`)}`},a=e=>{let t=e.type||``,n=[];for(let t of e.inputList||[])for(let e of t.fieldRow||[])e.name&&e.getValue&&n.push(`${e.name}=${e.getValue()}`);if(e.mutationToDom)try{let t=e.mutationToDom();t&&n.push(`mut:${t.outerHTML}`)}catch{}return`${t}|${n.join(`,`)}`},o=r.map(e=>i(e)),s=this.blocklyWorkspace.getTopBlocks(!1),c=s.map(e=>a(e)),l=Array(s.length).fill(!1),u=[];for(let e=0;e<o.length;e++){let t=!1;for(let n=0;n<c.length;n++)if(!l[n]&&o[e]===c[n]){l[n]=!0;let e=s[n].getRelativeToSurfaceXY();u.push({x:e.x,y:e.y}),t=!0;break}if(!t){let n=r[e].getAttribute(`type`)||``;for(let e=0;e<s.length;e++)if(!l[e]&&s[e].type===n){l[e]=!0;let n=s[e].getRelativeToSurfaceXY();u.push({x:n.x,y:n.y}),t=!0;break}}t||u.push(null)}let d=window.Blockly,f=d.utils.idGenerator.genUid();d.Events.setGroup(f),window.scripts.loading=!0;for(let e=0;e<s.length;e++)l[e]&&s[e].dispose(!1);if(r.length>1){let e=new Set;for(let t of r)e.add(`${t.getAttribute(`x`)||`0`},${t.getAttribute(`y`)||`0`}`);if(e.size===1){let e=10;for(let t of r)t.setAttribute(`x`,`10`),t.setAttribute(`y`,String(e)),e+=200}}e.Blockly.Xml.appendDomToWorkspace(n,this.blocklyWorkspace);let p=this.blocklyWorkspace.getTopBlocks(!1),m=p.slice(-r.length),h=10;for(let e of p.slice(0,-r.length)){let t=e.getRelativeToSurfaceXY(),n=e.getHeightWidth();h=Math.max(h,t.y+n.height+30)}for(let e=0;e<m.length;e++){let t=u[e];if(t){let n=m[e].getRelativeToSurfaceXY();m[e].moveBy(t.x-n.x,t.y-n.y)}else{let t=m[e].getRelativeToSurfaceXY();m[e].moveBy(10-t.x,h-t.y),h+=m[e].getHeightWidth().height+20}}window.scripts.loading=!1,d.Events.setGroup(!1),this.onBlocklyChanged()}catch(e){var n;window.scripts.loading=!1,(n=window.Blockly)==null||(n=n.Events)==null||n.setGroup(!1),console.error(`Error applying AI blocks:`,e)}}getWorkspaceXml(){if(!this.blocklyWorkspace)return``;let t=e.Blockly.Xml.workspaceToDom(this.blocklyWorkspace);return e.Blockly.Xml.domToPrettyText(t)}blocklyCode2JSCode(t){if(!this.blocklyWorkspace)return``;let n=e.Blockly.JavaScript.workspaceToCode(this.blocklyWorkspace);if(!t){n+=`
81
+ `;let t=e.Blockly.Xml.workspaceToDom(this.blocklyWorkspace),r=e.Blockly.Xml.domToText(t);n+=`//${btoa(encodeURIComponent(r))}`}return n}exportBlocks(){if(!this.blocklyWorkspace)return;let t,n=e.Blockly.getSelected();if(n){let r=e.Blockly.Xml.blockToDom(n),i=n.getRelativeToSurfaceXY();r.setAttribute(`x`,(n.RTL?-i.x:i.x).toString()),r.setAttribute(`y`,i.y.toString()),t=e.Blockly.Xml.domToPrettyText(r)}else{let n=e.Blockly.Xml.workspaceToDom(this.blocklyWorkspace);t=e.Blockly.Xml.domToPrettyText(n)}this.setState({exportText:t})}importBlocks(){this.setState({importText:!0})}onImportBlocks(t){if(this.blocklyWorkspace&&(t=(t||``).trim(),t))try{t.startsWith(`<xml`)||(t=`<xml xmlns="https://developers.google.com/blockly/xml">${t}</xml>`),t=t.replace(/[\n\r]/g,``).replace(/<variables>.*<\/variables>/g,``),window.scripts.loading=!0;let n=e.Blockly.utils.xml.textToDom(t),r=Array.from(n.querySelectorAll(`:scope > block`));if(r.length>1){let e=new Set;for(let t of r)e.add(`${t.getAttribute(`x`)||`0`},${t.getAttribute(`y`)||`0`}`);if(e.size===1){let e=parseInt(r[0].getAttribute(`y`)||`0`,10);for(let t of r)t.setAttribute(`y`,String(e)),e+=200}}if(e.Blockly.Xml.appendDomToWorkspace(n,this.blocklyWorkspace),r.length>1){let e=this.blocklyWorkspace.getTopBlocks(!1).slice(-r.length);if(e.length>1){let t=e[0].getRelativeToSurfaceXY().y;for(let n of e){let e=n.getRelativeToSurfaceXY();n.moveBy(0,t-e.y),t+=n.getHeightWidth().height+20}}}window.scripts.loading=!1,this.onBlocklyChanged()}catch(e){this.setState({error:{text:e.toString(),title:u.t(`Import error`)}})}}loadCode(){if(this.blocklyWorkspace){this.ignoreChanges=!0,this.blocklyWorkspace.clear();try{let t=e.jsCode2Blockly(this.originalCode)||`<xml xmlns="https://developers.google.com/blockly/xml"></xml>`;window.scripts.loading=!0;let n=e.Blockly.utils.xml.textToDom(t);e.Blockly.Xml.domToWorkspace(n,this.blocklyWorkspace),window.scripts.loading=!1}catch(e){console.error(e),setTimeout(()=>this.setState({error:u.t(`Cannot extract Blockly code!`)}))}setTimeout(()=>this.ignoreChanges=!1,100)}}onBlocklyChanged(){this.blocklyRemoveOrphanedShadows(),this.setState({changed:!0}),this.onChange()}async componentDidUpdate(){var t;if(!this.blockly||(this.didUpdate&&=(clearTimeout(this.didUpdate),null),this.blocklyWorkspace))return;window.addEventListener(`resize`,this.onResizeBind,!1),!this.resizeObserver&&this.blockly&&(this.resizeObserver=new ResizeObserver(()=>this.onResize()),this.resizeObserver.observe(this.blockly)),W||=await this.getToolbox(),G||=e.Blockly.utils.xml.textToDom(W),this.blocklyWorkspace=e.Blockly.inject(this.blockly,{renderer:`thrasos`,theme:this.state.themeType===`dark`?y():`classic`,media:`google-blockly/media/`,toolbox:G,zoom:{controls:!0,wheel:!1,startScale:1,maxScale:3,minScale:.3,scaleSpeed:1.2,pinch:!0},move:{scrollbars:{horizontal:!0,vertical:!0},drag:!0,wheel:!0},trashcan:!0,grid:{spacing:25,length:1,snap:!0},sounds:!1}),window.scripts={blocklyWorkspace:this.blocklyWorkspace},this.blocklyWorkspace.registerToolboxCategoryCallback(`PROCEDURE`,window.Blockly.Procedures.flyoutCategoryNew),this.blocklyWorkspace.addChangeListener(t=>{if(this.someSelected&&Date.now()-this.someSelectedTime>500){var n;let e=(n=this.blocklyWorkspace)==null?void 0:n.getAllBlocks();this.someSelected=null,e==null||e.forEach(e=>e.removeSelect())}[e.Blockly.Events.UI,e.Blockly.Events.CREATE,e.Blockly.Events.VIEWPORT_CHANGE].includes(t.type)||this.ignoreChanges||(this.changeTimer&&clearTimeout(this.changeTimer),this.changeTimer=setTimeout(()=>{this.changeTimer=null,this.onBlocklyChanged()},200))}),this.loadCode(),this.onResize();let n=document.getElementsByClassName(`blocklyToolboxDiv`)[0];if(this.blockly.appendChild(n),(t=window.Blockly)!=null&&(t=t.FieldOID)!=null&&t.DISPLAY_MODE_KEYS){let t=this.blocklyWorkspace,n=t.configureContextMenu;t.configureContextMenu=(r,i)=>{n&&n.call(t,r,i);let a=window.Blockly.FieldOID,o=a.DISPLAY_MODE_KEYS;for(let n=0;n<o.length;n++){var s,c;let i=((s=e.Blockly.Words)==null||(s=s[o[n]])==null?void 0:s[u.getLanguage()])||((c=e.Blockly.Words)==null||(c=c[o[n]])==null?void 0:c.en)||o[n];r.push({text:`${a.displayMode===n?`✓ `:` `}${i}`,enabled:!0,callback:()=>a.setDisplayMode(n,t),scope:{workspace:t},weight:200+n})}}}this.updateBackground(),setTimeout(()=>this.searchId(),200)}updateBackground(){if(this.state.themeType===`dark`){var t;(t=this.blocklyWorkspace)==null||t.setTheme(y())}else this.blocklyWorkspace&&(this.blocklyWorkspace.getThemeManager(),this.blocklyWorkspace.setTheme(e.Blockly.Themes.Classic))}componentWillUnmount(){this.appendBlocksFromXml,this.applyAiBlocks,this.getWorkspaceXml,this.blocklyWorkspace&&(this.blocklyWorkspace.dispose(),this.blocklyWorkspace=null,this.changeTimer&&clearTimeout(this.changeTimer),this.changeTimer=null,window.removeEventListener(`resize`,this.onResizeBind),this.resizeObserver&&=(this.resizeObserver.disconnect(),null))}onChange(){this.originalCode=this.blocklyCode2JSCode(),this.props.onChange&&this.props.onChange(this.originalCode)}async getToolbox(e){let t=window.document.getElementById(`toolbox`),n=t==null?void 0:t.outerHTML;if(!n)return e?(console.error(`Cannot load blocks!`),``):new Promise(e=>{setTimeout(()=>e(this.getToolbox(!0)),500)});if(n=n.replace(/{(\w+)}/g,(e,t)=>window.MSG[t]),window.Blockly.CustomBlocks){let e=``,t=u.getLanguage();for(let n=0;n<window.Blockly.CustomBlocks.length;n++){let r=window.Blockly.CustomBlocks[n],i=window.Blockly[r];e+=`<category name="${window.Blockly.Words[r][t]}" colour="${i.HUE}">`;for(let t in i.blocks)Object.prototype.hasOwnProperty.call(i.blocks,t)&&(e+=i.blocks[t]);e+=`</category>`}n=n.replace(`<category><block>%%CUSTOM_BLOCKS%%</block></category>`,e)}return n}renderMessageDialog(){return this.state.message?n(f,{text:typeof this.state.message==`object`?this.state.message.text:this.state.message,title:typeof this.state.message==`object`?this.state.message.title:``,onClose:()=>this.setState({message:``})},`dialogMessage`):null}renderErrorDialog(){return this.state.error?n(v,{text:typeof this.state.error==`object`?this.state.error.text.toString():this.state.error,title:typeof this.state.error==`object`?this.state.error.title:``,onClose:()=>{this.blinkBlock&&=(e.blocklyBlinkBlock(this.blinkBlock),null),this.setState({error:``})}},`dialogError`):null}renderExportDialog(){return this.state.exportText?n(g,{themeType:this.state.themeType,onClose:()=>this.setState({exportText:``}),text:this.state.exportText,scriptId:this.props.scriptId},`dialogExport`):null}renderImportDialog(){return this.state.importText?n(_,{themeType:this.props.themeType,onClose:e=>{this.setState({importText:!1}),this.onImportBlocks(e)}},`dialogImport`):null}renderDialogPrompt(){return this.state.showInputPrompt?i(s,{onClose:()=>{var e;let t=(e=this.state.showInputPrompt)==null?void 0:e.callback;t&&t(null),this.setState({showInputPrompt:null})},maxWidth:`sm`,fullWidth:!0,open:!0,children:[n(t,{children:this.state.showInputPrompt.promptText}),n(c,{children:n(r,{variant:`standard`,fullWidth:!0,autoFocus:!0,value:this.state.showInputPrompt.value,onKeyUp:e=>{if(e.key===`Enter`){var t,n;let e=(t=this.state.showInputPrompt)==null?void 0:t.callback,r=(n=this.state.showInputPrompt)==null?void 0:n.value;e&&e(r===void 0?null:r),this.setState({showInputPrompt:null})}},onChange:e=>{var t;let n={...this.state.showInputPrompt};if((t=this.state.showInputPrompt)!=null&&t.callback){var r;n.callback=(r=this.state.showInputPrompt)==null?void 0:r.callback}n.value=e.target.value,this.setState({showInputPrompt:n})}})}),i(o,{children:[n(h,{variant:`contained`,disabled:!this.state.showInputPrompt.value,onClick:()=>{var e,t;let n=(e=this.state.showInputPrompt)==null?void 0:e.callback,r=(t=this.state.showInputPrompt)==null?void 0:t.value;n&&n(r===void 0?null:r),this.setState({showInputPrompt:null})},color:`primary`,startIcon:n(l,{}),children:u.t(`Apply`)}),n(h,{color:`grey`,variant:`contained`,onClick:()=>{var e;let t=(e=this.state.showInputPrompt)==null?void 0:e.callback;t&&t(null),this.setState({showInputPrompt:null})},startIcon:n(p,{}),children:u.t(`Close`)})]})]},`inputDialog`):null}render(){return this.state.languageBlocklyLoaded&&this.state.languageOwnLoaded?(this.didUpdate=setTimeout(()=>{this.didUpdate=null,this.componentDidUpdate()},100),[n(`div`,{ref:e=>{this.blockly=e},style:{width:`100%`,height:`100%`,position:`relative`}},`blocklyDOM`),this.renderDialogPrompt(),this.renderMessageDialog(),this.renderErrorDialog(),this.renderExportDialog(),this.renderImportDialog()]):null}};d(J,`Blockly`,window.Blockly);export{V as n,J as t};