iobroker.javascript
Version:
Rules Engine for ioBroker
14 lines (10 loc) • 15.2 kB
JavaScript
import{c as ie,j as n}from"./createSvgIcon-DPvF8xqu.js";import{j as S,b as H,k as J,c as re}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as F,a as Q,b as Z,i as $,h as X,c as oe,$ as ae,d as ce,e as le,f as de,g as ee}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{_ as l}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{_ as me}from"./preload-helper-BDBacUwf.js";import{C as he,b as ue,R as fe}from"./index-gIA8x-8f.js";import pe from"./ScriptEditorVanillaMonaco-DSYvOslZ.js";import{c as te,I as ge}from"./index-C49cpVll.js";import{h as ye}from"./index-XSrHkgLE.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-D-eF6r8M.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-B0Ba5G9z.js";const ve=ie(n.jsx("path",{d:"M11.07 12.85c.77-1.39 2.25-2.21 3.11-3.44.91-1.29.4-3.7-2.18-3.7-1.69 0-2.52 1.28-2.87 2.34L6.54 6.96C7.25 4.83 9.18 3 11.99 3c2.35 0 3.96 1.07 4.78 2.41.7 1.15 1.11 3.3.03 4.9-1.2 1.77-2.35 2.31-2.97 3.45-.25.46-.35.76-.35 2.24h-2.89c-.01-.78-.13-2.05.48-3.15M14 20c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2"}),"QuestionMark"),je=me(()=>import("./docs-BrInh2Pn.js"),[],import.meta.url);let G=null;async function xe(s){if(G)return G;const f=await s.getObjectViewSystem("state","","香"),r=await s.getObjectViewSystem("channel","","香"),v=await s.getObjectViewSystem("device","","香"),d=await s.getObjectViewSystem("folder","","香"),k=await s.getObjectViewSystem("enum","","香");return G=Object.assign(f,r,v,d,k),G}function V(s,f){return s&&typeof s=="object"?s[f]||s.en:s||""}async function Ie(s){var P,N,L,K;const f=l.I18n.getLanguage(),r=await xe(s),v=Object.keys(r).sort(),d=new he,k=[],A=["UNREACH_STICKY"],W=[ue.Types.info],_=[],b=[],R=[],D=[];v.forEach(m=>{var a,h,c;((a=r[m])==null?void 0:a.type)==="enum"?_.push(m):(c=(h=r[m])==null?void 0:h.common)!=null&&c.smartName&&D.push(m)}),_.forEach(m=>{m.startsWith("enum.rooms.")?b.push(m):m.startsWith("enum.functions.")&&R.push(m);const a=r[m].common.members;a!=null&&a.length&&a.forEach(h=>{r[h]&&(D.includes(h)||D.push(h))})});const M={id:"",objects:r,_keysOptional:v,_usedIdsOptional:k,ignoreIndicators:A,excludedTypes:W},E=[];D.forEach(m=>{M.id=m;const a=d.detect(M);a&&a.forEach(h=>{var w;const c=(w=h.states.find(i=>i.id))==null?void 0:w.id;if(!c||E.find(i=>i.id===c))return;const j=r[c],z={id:c,name:V(j.common.name,f),type:j.type,deviceType:h.type,states:h.states.filter(i=>i.id).map(i=>({id:i.id,name:i.name,role:i.defaultRole,type:r[i.id].common.type,unit:r[i.id].common.unit,read:r[i.id].common.read===void 0?!0:r[i.id].common.read,write:r[i.id].common.write===void 0?!0:r[i.id].common.write}))},T=c.split(".");let e,o;(j.type==="channel"||j.type==="state")&&(T.pop(),e=T.join("."),r[e]&&(r[e].type==="channel"||r[e].type==="folder")?(T.pop(),o=T.join("."),(!r[o]||r[o].type!=="device"&&r[e].type!=="folder")&&(o=void 0)):e=void 0);const I=b.find(i=>{var x,p,t;return(x=r[i].common.members)!=null&&x.includes(c)||e&&((p=r[i].common.members)!=null&&p.includes(e))?!0:o&&((t=r[i].common.members)==null?void 0:t.includes(o))});I&&(z.room=V(r[I].common.name,f));const g=R.find(i=>{var x,p,t;return(x=r[i].common.members)!=null&&x.includes(c)||e&&((p=r[i].common.members)!=null&&p.includes(e))?!0:o&&((t=r[i].common.members)==null?void 0:t.includes(o))});g&&(z.function=V(r[g].common.name,f)),E.push(z)})});for(let m=0;m<E.length;m++){const a=E[m];if(a.type==="state"||a.type==="channel"){const h=a.id.split(".");h.pop();const c=r[h.join(".")];if(c&&(c.type==="channel"||c.type==="device"||c.type==="folder")){a.name=V(((P=c.common)==null?void 0:P.name)||a.name,f),h.pop();const j=r[h.join(".")];(j==null?void 0:j.type)==="device"&&((N=j.common)!=null&&N.icon)&&(a.name=V(((L=j.common)==null?void 0:L.name)||a.name,f))}else a.name=V(((K=c==null?void 0:c.common)==null?void 0:K.name)||a.name,f)}}return E}const _e=async()=>(await je).default,we={ru:"Russian",en:"English",de:"German",es:"Spanish",fr:"French",it:"Italian",pl:"Polish",nl:"Dutch",pt:"Portuguese",uk:"Ukrainian","zh-cn":"Chinese"},Y={flexShrink:0,opacity:.7},ne={openai:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",style:Y,children:n.jsx("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.91 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.097 5.98 5.98 0 0 0 .51 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073zM13.26 22.43a4.476 4.476 0 0 1-2.876-1.04l.141-.081 4.779-2.758a.795.795 0 0 0 .392-.681v-6.737l2.02 1.168a.071.071 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494zM3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.759a.771.771 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646zM2.34 7.896a4.485 4.485 0 0 1 2.366-1.973V11.6a.766.766 0 0 0 .388.676l5.815 3.355-2.02 1.168a.076.076 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855-5.833-3.387L15.119 7.2a.076.076 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667zm2.01-3.023-.141-.085-4.774-2.782a.776.776 0 0 0-.785 0L9.409 9.23V6.897a.066.066 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.795.795 0 0 0-.393.681zm1.097-2.365 2.602-1.5 2.607 1.5v2.999l-2.597 1.5-2.607-1.5z"})}),anthropic:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",style:Y,children:n.jsx("path",{d:"M17.304 3.54h-3.604L7.128 20.46h3.604l1.345-3.462h6.932l1.345 3.462H24L17.304 3.54zm-3.45 10.696 2.647-6.812 2.647 6.812h-5.295zM6.696 3.54H3.092L0 20.46h3.604L6.696 3.54z"})}),gemini:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",style:Y,children:n.jsx("path",{d:"M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0z"})}),deepseek:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",style:Y,children:n.jsx("path",{d:"M5 3h6a9 9 0 0 1 0 18H5V3zm4 14V7h2a5 5 0 0 1 0 10H9z"})})};async function se(s,f){const r=Object.keys(f);for(let v=0;v<r.length;v++){const d=await s.getObject(r[v]),k=((d==null?void 0:d.native.gptKey)||"").trim(),A=((d==null?void 0:d.native.claudeKey)||"").trim(),W=((d==null?void 0:d.native.geminiKey)||"").trim(),_=((d==null?void 0:d.native.deepseekKey)||"").trim(),b=((d==null?void 0:d.native.gptBaseUrl)||"").trim()||void 0;if(k||A||W||_||b)return{gptKey:k,claudeKey:A,geminiKey:W,deepseekKey:_,gptBaseUrl:b}}return null}const De=s=>{const[f,r]=S(window.localStorage.getItem("openai-question")||""),[v,d]=S(""),[k,A]=S(!1),[W,_]=S(!1),[b,R]=S(window.localStorage.getItem("openai-model")||""),[D,M]=S(!1),[E,P]=S([]),[N,L]=S(!0),[K,m]=S(null),a=H(null),h=H(null),c=H({}),j=H(null),z=J(async e=>{L(!0),m(null);try{const o=await se(s.socket,s.runningInstances);if(e!=null&&e.current)return;if(!o){L(!1);return}h.current=o;const I=Object.keys(s.runningInstances)[0];if(!I){m(l.I18n.t("No running javascript instance found")),L(!1);return}const g=[],w={},i=[],x=[],p=(t,B)=>{for(const O of t){const C=O.toLowerCase();C.includes("embedding")||C.includes("moderation")||C.startsWith("dall-e")||C.startsWith("tts-")||C.startsWith("whisper")||C.startsWith("babbage")||C.startsWith("davinci")||C.startsWith("sora")||C.startsWith("omni-moderation")||w[O]||(g.push(O),w[O]=B)}};if((o.gptKey||o.gptBaseUrl)&&x.push(s.socket.sendTo(I,"testApiConnection",{apiKey:o.gptKey,baseUrl:o.gptBaseUrl||"",provider:"openai"}).then(t=>{t.models?p(t.models,"openai"):t.error&&i.push(`OpenAI: ${t.error}`)}).catch(t=>{i.push(`OpenAI: ${String(t)}`)})),o.claudeKey&&x.push(s.socket.sendTo(I,"testApiConnection",{apiKey:o.claudeKey,provider:"anthropic"}).then(t=>{t.models?p(t.models,"anthropic"):t.error&&i.push(`Anthropic: ${t.error}`)}).catch(t=>{i.push(`Anthropic: ${String(t)}`)})),o.geminiKey&&x.push(s.socket.sendTo(I,"testApiConnection",{apiKey:o.geminiKey,provider:"gemini"}).then(t=>{t.models?p(t.models,"gemini"):t.error&&i.push(`Gemini: ${t.error}`)}).catch(t=>{i.push(`Gemini: ${String(t)}`)})),o.deepseekKey&&x.push(s.socket.sendTo(I,"testApiConnection",{apiKey:o.deepseekKey,provider:"deepseek"}).then(t=>{t.models?p(t.models,"deepseek"):t.error&&i.push(`DeepSeek: ${t.error}`)}).catch(t=>{i.push(`DeepSeek: ${String(t)}`)})),await Promise.all(x),e!=null&&e.current)return;if(c.current=w,g.length>0){g.sort(),P(g);const t=window.localStorage.getItem("openai-model");t&&g.includes(t)?R(t):R(g[0])}i.length>0&&m(i.join("; "))}catch(o){console.error("Failed to fetch models:",o),e!=null&&e.current||m(l.I18n.t("Request failed: %s",String(o)))}e!=null&&e.current||L(!1)},[s.socket,s.runningInstances]);re(()=>{const e={current:!1};return z(e),()=>{e.current=!0}},[z]);const T=J(async()=>{let e;a.current?e=a.current:(e=await Ie(s.socket),a.current=e,console.log(`devices: ${JSON.stringify(e,null,2)}`));let o=h.current;o||(o=await se(s.socket,s.runningInstances),h.current=o);let I;if(j.current?I=j.current:(I=await _e(),j.current=I),!o){M(!0);return}const g=c.current[b];if(!g){_(l.I18n.t("Please select a valid model"));return}let w,i;g==="anthropic"?(w=o.claudeKey,i=""):g==="gemini"?(w=o.geminiKey,i=""):g==="deepseek"?(w=o.deepseekKey,i=""):(w=o.gptKey,i=o.gptBaseUrl||"");const x=Object.keys(s.runningInstances)[0];if(!x){_(l.I18n.t("No running javascript instance found"));return}A(!0),_(!1);try{const p=await s.socket.sendTo(x,"chatCompletion",{apiKey:w,baseUrl:i,model:b,provider:g,messages:[{role:"system",content:`You are programmer. Here is a documentation:
${I}`},{role:"system",content:`Here is list of devices:
${JSON.stringify(e,null,2)}`},{role:"user",content:`Write JavaScript code that does:
${f}
Return only code.
Write comments in ${we[l.I18n.getLanguage()]||"English"}.
You can call async function directly in the code without encapsulate them in async function as this code will be already executed in async function.
Do not import any libraries as all functions are already imported.`}]});if(p.error)_(p.error);else{let t=p.content||"";t=t.replace(/<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,"");const B=t.match(/```(?:javascript|js|typescript)?\n?([\s\S]*?)```/m);let O;if(B)O=B[1].trim();else{const C=t.split(`
`),U=[];let q=!1;for(const y of C){const u=y.trim();!q&&u===""||(!q&&(u.startsWith("//")||u.startsWith("const ")||u.startsWith("let ")||u.startsWith("var ")||u.startsWith("function ")||u.startsWith("async ")||u.startsWith("await ")||u.startsWith("if ")||u.startsWith("for ")||u.startsWith("on(")||u.startsWith("schedule(")||u.startsWith("setState")||u.startsWith("getState")||u.startsWith("createState")||u.startsWith("$")||u.startsWith("'use strict'")||u.startsWith('"use strict"'))&&(q=!0),q&&U.push(y))}for(;U.length>0;){const y=U[U.length-1].trim();if(y===""||y.length>0&&!y.startsWith("//")&&!y.startsWith("*")&&!y.startsWith("}")&&!y.startsWith(");")&&!y.endsWith(";")&&!y.endsWith("}")&&!y.endsWith(")")&&!y.endsWith(",")&&!y.endsWith("{")&&/^[A-Z]/.test(y))U.pop();else break}O=U.join(`
`).trim()}d(O||"")}}catch(p){console.error("Chat request failed:",p),_(l.I18n.t("Request failed: %s",String(p)))}A(!1)},[f,b,s.runningInstances,s.socket]);return n.jsxs(F,{maxWidth:"lg",sx:{"& .MuiDialog-paper":{height:"calc(100% - 100px)"}},open:!0,onClose:()=>s.onClose(),fullWidth:!0,children:[D&&n.jsxs(F,{maxWidth:"lg",open:!0,onClose:()=>M(!1),fullWidth:!0,children:[n.jsx(Q,{children:l.I18n.t("No API key found")}),n.jsxs(Z,{style:{display:"flex",flexDirection:"column",gap:8},children:[n.jsx("div",{children:l.I18n.t("You have to enter at least one API key in the configuration of javascript adapter.")}),n.jsx($,{variant:"contained",onClick:()=>{const e=Object.keys(s.runningInstances);window.open(`../../#tab-instances/config/${e[0]||"system.adapter.javascript.0"}`,"_blank"),M(!1)},children:l.I18n.t("Open configuration")})]}),n.jsx(X,{children:n.jsx($,{variant:"contained",startIcon:n.jsx(te,{}),onClick:()=>M(!1),children:l.I18n.t("Close")})})]}),n.jsx(Q,{children:l.I18n.t("AI code generator")}),n.jsxs(Z,{style:{display:"flex",flexDirection:"column",gap:8,height:"100%"},children:[n.jsx("div",{children:n.jsx(oe,{variant:"standard",multiline:!0,autoFocus:!0,disabled:k,fullWidth:!0,onKeyUp:e=>{e.key==="Enter"&&e.ctrlKey&&T()},label:l.I18n.t("Enter your question"),helperText:l.I18n.t("Press Ctrl+Enter to get the answer"),value:f,onChange:e=>{window.localStorage.setItem("openai-question",e.target.value),r(e.target.value)}})}),n.jsxs("div",{style:{display:"flex",alignItems:"baseline"},children:[n.jsx($,{variant:"contained",disabled:k||!f||!b,startIcon:n.jsx(ve,{}),onClick:async()=>T(),children:k?n.jsx(ae,{size:24}):l.I18n.t("Ask")}),n.jsxs(ce,{style:{width:300,marginLeft:20},disabled:k,variant:"standard",error:!!K,children:[n.jsx(le,{children:l.I18n.t("Model")}),n.jsxs(de,{variant:"standard",value:b,disabled:N||!!K,renderValue:e=>n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[ne[c.current[e]],e]}),onChange:e=>{window.localStorage.setItem("openai-model",e.target.value),W&&_(!1),R(e.target.value)},children:[N&&n.jsx(ee,{value:"",disabled:!0,children:l.I18n.t("Loading models...")}),E.map(e=>n.jsx(ee,{value:e,children:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[ne[c.current[e]],e]})},e))]})]}),K&&n.jsx($,{style:{marginLeft:10},variant:"outlined",color:"error",startIcon:n.jsx(fe,{}),onClick:()=>{z()},children:l.I18n.t("Retry")})]}),K&&n.jsx("div",{style:{color:s.themeType==="dark"?"#984242":"#bb0000"},children:K}),n.jsx("div",{children:l.I18n.t("Result")}),n.jsx("div",{style:{height:"calc(100% - 155px)"},children:W?n.jsx("div",{style:{color:s.themeType==="dark"?"#984242":"#bb0000"},children:W}):n.jsx(pe,{triggerPrettier:1,adapterName:s.adapterName,runningInstances:s.runningInstances,style:{height:"100%",width:"100%",resize:"none"},name:"ai",socket:s.socket,readOnly:!0,checkJs:!0,code:v,isDark:s.themeType==="dark",language:s.language||"javascript"})})]}),n.jsxs(X,{children:[n.jsx($,{color:"grey",variant:"outlined",disabled:!v,startIcon:n.jsx(ye,{}),onClick:()=>{l.Utils.copyToClipboard(v),window.alert(l.I18n.t("Copied"))},children:l.I18n.t("Copy to clipboard")}),n.jsx($,{color:"primary",variant:"contained",disabled:!v||!!W,startIcon:n.jsx(ge,{}),onClick:()=>{s.onAddCode(v),s.onClose()},children:l.I18n.t("Use generated code")}),n.jsx($,{color:"grey",variant:"contained",startIcon:n.jsx(te,{}),onClick:()=>s.onClose(),children:l.I18n.t("Close")})]})]})};export{De as default};