diff --git a/endpoints/lollms_apps.py b/endpoints/lollms_apps.py index 24c52da6..e2465ff6 100644 --- a/endpoints/lollms_apps.py +++ b/endpoints/lollms_apps.py @@ -17,6 +17,8 @@ import uuid import platform from ascii_colors import ASCIIColors, trace_exception import pipmaster as pm +import sys + if not pm.is_installed("httpx"): pm.install("httpx") import httpx @@ -293,30 +295,33 @@ async def upload_app(client_id: str, file: UploadFile = File(...)): shutil.rmtree(temp_dir) +import shutil +from pathlib import Path + @router.post("/install/{app_name}") async def install_app(app_name: str, auth: AuthRequest): check_access(lollmsElfServer, auth.client_id) REPO_DIR = lollmsElfServer.lollms_paths.personal_path/"apps_zoo_repo" # Create the app directory - app_path = lollmsElfServer.lollms_paths.apps_zoo_path/app_name # Adjust the path as needed + app_path = lollmsElfServer.lollms_paths.apps_zoo_path/app_name os.makedirs(app_path, exist_ok=True) - # Define the local paths for the files to copy - files_to_copy = { - "icon.png": REPO_DIR/app_name/"icon.png", - "description.yaml": REPO_DIR/app_name/"description.yaml", - "index.html": REPO_DIR/app_name/"index.html" - } + source_dir = REPO_DIR/app_name + + if not source_dir.exists(): + raise HTTPException(status_code=404, detail=f"App {app_name} not found in the local repository") - # Copy each file from the local repo - for file_name, local_path in files_to_copy.items(): - if local_path.exists(): - with open(local_path, 'rb') as src_file: - with open(app_path/file_name, 'wb') as dest_file: - dest_file.write(src_file.read()) + # Define directories to exclude + exclude_dirs = {'.vscode', '.git'} + + # Copy all files and directories, excluding the ones in exclude_dirs + for item in source_dir.glob('*'): + if item.is_dir(): + if item.name not in exclude_dirs: + shutil.copytree(item, app_path/item.name, dirs_exist_ok=True) else: - raise HTTPException(status_code=404, detail=f"{file_name} not found in the local repository") + shutil.copy2(item, app_path) return {"message": f"App {app_name} installed successfully."} @@ -453,12 +458,40 @@ async def fetch_github_apps(): apps = load_apps_data() return {"apps": apps} + +def install_requirements(app_path: Path): + requirements_file = app_path / "requirements.txt" + if requirements_file.exists(): + try: + subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", str(requirements_file)]) + print("Requirements installed successfully.") + except subprocess.CalledProcessError as e: + print(f"Error installing requirements: {e}") + raise + def run_server(app_path: Path): server_script = app_path / "server.py" if server_script.exists(): - subprocess.Popen(["python", str(server_script)], cwd=str(app_path)) + try: + # Install requirements if they exist + install_requirements(app_path) + + # Determine the platform and open a terminal to execute the Python code. + system = platform.system() + if system == "Windows": + process = subprocess.Popen(f"""start cmd /k "cd /d "{app_path}" && python "{server_script}" && pause" """, shell=True) + elif system == "Darwin": # macOS + process = subprocess.Popen(["open", "-a", "Terminal", f'cd "{app_path}" && python "{server_script}"'], shell=True) + elif system == "Linux": + process = subprocess.Popen(["x-terminal-emulator", "-e", f'bash -c "cd \\"{app_path}\\" && python \\"{server_script}\\"; exec bash"'], shell=True) + else: + raise Exception(f"Unsupported platform: {system}") + + except Exception as ex: + # Stop the timer. + ASCIIColors.error(f"Error executing Python code: {ex}") else: - print(f"Server script not found for app: {app_path.name}") + ASCIIColors.error(f"Server script not found for app: {app_path.name}") @router.post("/apps/start_server") async def start_app_server(request: OpenFolderRequest): @@ -473,6 +506,6 @@ async def start_app_server(request: OpenFolderRequest): raise HTTPException(status_code=404, detail="Server script not found for this app") # Start the server in the background - background_tasks.add_task(run_server, app_path) + run_server(app_path) - return {"status": "success", "message": f"Server for {app_name} is starting"} \ No newline at end of file + return {"status": "success", "message": f"Server for {app_path} is starting"} diff --git a/web/dist/assets/index-7542a266.js b/web/dist/assets/index-8ff9ab0f.js similarity index 99% rename from web/dist/assets/index-7542a266.js rename to web/dist/assets/index-8ff9ab0f.js index 67a9cf1c..f95ac38a 100644 --- a/web/dist/assets/index-7542a266.js +++ b/web/dist/assets/index-8ff9ab0f.js @@ -3904,4 +3904,5 @@ void main() { Please check that you don't accidentally use the same token twice to register two different handlers for the same event/hook.`),this.unsubscribe(e)),this.listenerMap.set(e,n),this._listeners.push(n)}unsubscribe(e){if(this.listenerMap.has(e)){const n=this.listenerMap.get(e);this.listenerMap.delete(e);const s=this._listeners.indexOf(n);s>=0&&this._listeners.splice(s,1)}}registerProxy(e,n){this.proxyMap.has(e)&&(console.warn(`Already subscribed. Unsubscribing for you. Please check that you don't accidentally use the same token twice to register two different proxies for the same event/hook.`),this.unregisterProxy(e)),this.proxyMap.set(e,n),this.proxies.push(n)}unregisterProxy(e){if(!this.proxyMap.has(e))return;const n=this.proxyMap.get(e);this.proxyMap.delete(e);const s=this.proxies.indexOf(n);s>=0&&this.proxies.splice(s,1)}}class Ht extends Kr{constructor(e){super(),this.entity=e}emit(e){this.listeners.forEach(n=>n(e,this.entity))}}class In extends Kr{constructor(e){super(),this.entity=e}emit(e){let n=!1;const s=()=>[n=!0];for(const i of Array.from(this.listeners.values()))if(i(e,s,this.entity),n)return{prevented:!0};return{prevented:!1}}}class zO extends Kr{execute(e,n){let s=e;for(const i of this.listeners)s=i(s,n);return s}}class ts extends zO{constructor(e){super(),this.entity=e}execute(e){return super.execute(e,this.entity)}}class XDt extends Kr{constructor(e){super(),this.entity=e}execute(e){const n=[];for(const s of this.listeners)n.push(s(e,this.entity));return n}}function Vs(){const t=Symbol(),e=new Map,n=new Set,s=(c,u)=>{u instanceof Kr&&u.registerProxy(t,()=>{var d,h;return(h=(d=e.get(c))===null||d===void 0?void 0:d.listeners)!==null&&h!==void 0?h:[]})},i=c=>{const u=new Kr;e.set(c,u),n.forEach(d=>s(c,d[c]))},r=c=>{n.add(c);for(const u of e.keys())s(u,c[u])},o=c=>{for(const u of e.keys())c[u]instanceof Kr&&c[u].unregisterProxy(t);n.delete(c)},a=()=>{n.forEach(c=>o(c)),e.clear()};return new Proxy({},{get(c,u){return u==="addTarget"?r:u==="removeTarget"?o:u==="destroy"?a:typeof u!="string"||u.startsWith("_")?c[u]:(e.has(u)||i(u),e.get(u))}})}class Z1{constructor(e,n){if(this.destructed=!1,this.events={destruct:new Ht(this)},!e||!n)throw new Error("Cannot initialize connection with null/undefined for 'from' or 'to' values");this.id=Ri(),this.from=e,this.to=n,this.from.connectionCount++,this.to.connectionCount++}destruct(){this.events.destruct.emit(),this.from.connectionCount--,this.to.connectionCount--,this.destructed=!0}}class HO{constructor(e,n){if(!e||!n)throw new Error("Cannot initialize connection with null/undefined for 'from' or 'to' values");this.id=Ri(),this.from=e,this.to=n}}function Wg(t,e){return Object.fromEntries(Object.entries(t).map(([n,s])=>[n,e(s)]))}class qO{constructor(){this._title="",this.id=Ri(),this.events={loaded:new Ht(this),beforeAddInput:new In(this),addInput:new Ht(this),beforeRemoveInput:new In(this),removeInput:new Ht(this),beforeAddOutput:new In(this),addOutput:new Ht(this),beforeRemoveOutput:new In(this),removeOutput:new Ht(this),beforeTitleChanged:new In(this),titleChanged:new Ht(this),update:new Ht(this)},this.hooks={beforeLoad:new ts(this),afterSave:new ts(this)}}get graph(){return this.graphInstance}get title(){return this._title}set title(e){this.events.beforeTitleChanged.emit(e).prevented||(this._title=e,this.events.titleChanged.emit(e))}addInput(e,n){return this.addInterface("input",e,n)}addOutput(e,n){return this.addInterface("output",e,n)}removeInput(e){return this.removeInterface("input",e)}removeOutput(e){return this.removeInterface("output",e)}registerGraph(e){this.graphInstance=e}load(e){this.hooks.beforeLoad.execute(e),this.id=e.id,this._title=e.title,Object.entries(e.inputs).forEach(([n,s])=>{this.inputs[n]&&(this.inputs[n].load(s),this.inputs[n].nodeId=this.id)}),Object.entries(e.outputs).forEach(([n,s])=>{this.outputs[n]&&(this.outputs[n].load(s),this.outputs[n].nodeId=this.id)}),this.events.loaded.emit(this)}save(){const e=Wg(this.inputs,i=>i.save()),n=Wg(this.outputs,i=>i.save()),s={type:this.type,id:this.id,title:this.title,inputs:e,outputs:n};return this.hooks.afterSave.execute(s)}onPlaced(){}onDestroy(){}initializeIo(){Object.entries(this.inputs).forEach(([e,n])=>this.initializeIntf("input",e,n)),Object.entries(this.outputs).forEach(([e,n])=>this.initializeIntf("output",e,n))}initializeIntf(e,n,s){s.isInput=e==="input",s.nodeId=this.id,s.events.setValue.subscribe(this,()=>this.events.update.emit({type:e,name:n,intf:s}))}addInterface(e,n,s){const i=e==="input"?this.events.beforeAddInput:this.events.beforeAddOutput,r=e==="input"?this.events.addInput:this.events.addOutput,o=e==="input"?this.inputs:this.outputs;return i.emit(s).prevented?!1:(o[n]=s,this.initializeIntf(e,n,s),r.emit(s),!0)}removeInterface(e,n){const s=e==="input"?this.events.beforeRemoveInput:this.events.beforeRemoveOutput,i=e==="input"?this.events.removeInput:this.events.removeOutput,r=e==="input"?this.inputs[n]:this.outputs[n];if(!r||s.emit(r).prevented)return!1;if(r.connectionCount>0)if(this.graphInstance)this.graphInstance.connections.filter(a=>a.from===r||a.to===r).forEach(a=>{this.graphInstance.removeConnection(a)});else throw new Error("Interface is connected, but no graph instance is specified. Unable to delete interface");return r.events.setValue.unsubscribe(this),e==="input"?delete this.inputs[n]:delete this.outputs[n],i.emit(r),!0}}let YO=class extends qO{load(e){super.load(e)}save(){return super.save()}};function Ua(t){return class extends YO{constructor(){var e,n;super(),this.type=t.type,this.inputs={},this.outputs={},this.calculate=t.calculate?(s,i)=>t.calculate.call(this,s,i):void 0,this._title=(e=t.title)!==null&&e!==void 0?e:t.type,this.executeFactory("input",t.inputs),this.executeFactory("output",t.outputs),(n=t.onCreate)===null||n===void 0||n.call(this)}onPlaced(){var e;(e=t.onPlaced)===null||e===void 0||e.call(this)}onDestroy(){var e;(e=t.onDestroy)===null||e===void 0||e.call(this)}executeFactory(e,n){Object.keys(n||{}).forEach(s=>{const i=n[s]();e==="input"?this.addInput(s,i):this.addOutput(s,i)})}}}class Xt{set connectionCount(e){this._connectionCount=e,this.events.setConnectionCount.emit(e)}get connectionCount(){return this._connectionCount}set value(e){this.events.beforeSetValue.emit(e).prevented||(this._value=e,this.events.setValue.emit(e))}get value(){return this._value}constructor(e,n){this.id=Ri(),this.nodeId="",this.port=!0,this.hidden=!1,this.events={setConnectionCount:new Ht(this),beforeSetValue:new In(this),setValue:new Ht(this),updated:new Ht(this)},this.hooks={load:new ts(this),save:new ts(this)},this._connectionCount=0,this.name=e,this._value=n}load(e){this.id=e.id,this.templateId=e.templateId,this.value=e.value,this.hooks.load.execute(e)}save(){const e={id:this.id,templateId:this.templateId,value:this.value};return this.hooks.save.execute(e)}setComponent(e){return this.component=e,this}setPort(e){return this.port=e,this}setHidden(e){return this.hidden=e,this}use(e,...n){return e(this,...n),this}}const ga="__baklava_SubgraphInputNode",ba="__baklava_SubgraphOutputNode";class $O extends YO{constructor(){super(),this.graphInterfaceId=Ri()}onPlaced(){super.onPlaced(),this.initializeIo()}save(){return{...super.save(),graphInterfaceId:this.graphInterfaceId}}load(e){super.load(e),this.graphInterfaceId=e.graphInterfaceId}}class WO extends $O{constructor(){super(...arguments),this.type=ga,this.inputs={name:new Xt("Name","Input")},this.outputs={placeholder:new Xt("Value",void 0)}}static isGraphInputNode(e){return e.type===ga}}class KO extends $O{constructor(){super(...arguments),this.type=ba,this.inputs={name:new Xt("Name","Output"),placeholder:new Xt("Value",void 0)},this.outputs={output:new Xt("Output",void 0).setHidden(!0)},this.calculate=({placeholder:e})=>({output:e})}static isGraphOutputNode(e){return e.type===ba}}class ec{get nodes(){return this._nodes}get connections(){return this._connections}get loading(){return this._loading}get destroying(){return this._destroying}get inputs(){return this.nodes.filter(n=>n.type===ga).map(n=>({id:n.graphInterfaceId,name:n.inputs.name.value,nodeId:n.id,nodeInterfaceId:n.outputs.placeholder.id}))}get outputs(){return this.nodes.filter(n=>n.type===ba).map(n=>({id:n.graphInterfaceId,name:n.inputs.name.value,nodeId:n.id,nodeInterfaceId:n.outputs.output.id}))}constructor(e,n){this.id=Ri(),this.activeTransactions=0,this._nodes=[],this._connections=[],this._loading=!1,this._destroying=!1,this.events={beforeAddNode:new In(this),addNode:new Ht(this),beforeRemoveNode:new In(this),removeNode:new Ht(this),beforeAddConnection:new In(this),addConnection:new Ht(this),checkConnection:new In(this),beforeRemoveConnection:new In(this),removeConnection:new Ht(this)},this.hooks={save:new ts(this),load:new ts(this),checkConnection:new XDt(this)},this.nodeEvents=Vs(),this.nodeHooks=Vs(),this.connectionEvents=Vs(),this.editor=e,this.template=n,e.registerGraph(this)}addNode(e){if(!this.events.beforeAddNode.emit(e).prevented)return this.nodeEvents.addTarget(e.events),this.nodeHooks.addTarget(e.hooks),e.registerGraph(this),this._nodes.push(e),e=this.nodes.find(n=>n.id===e.id),e.onPlaced(),this.events.addNode.emit(e),e}removeNode(e){if(this.nodes.includes(e)){if(this.events.beforeRemoveNode.emit(e).prevented)return;const n=[...Object.values(e.inputs),...Object.values(e.outputs)];this.connections.filter(s=>n.includes(s.from)||n.includes(s.to)).forEach(s=>this.removeConnection(s)),this._nodes.splice(this.nodes.indexOf(e),1),this.events.removeNode.emit(e),e.onDestroy(),this.nodeEvents.removeTarget(e.events),this.nodeHooks.removeTarget(e.hooks)}}addConnection(e,n){const s=this.checkConnection(e,n);if(!s.connectionAllowed||this.events.beforeAddConnection.emit({from:e,to:n}).prevented)return;for(const r of s.connectionsInDanger){const o=this.connections.find(a=>a.id===r.id);o&&this.removeConnection(o)}const i=new Z1(s.dummyConnection.from,s.dummyConnection.to);return this.internalAddConnection(i),i}removeConnection(e){if(this.connections.includes(e)){if(this.events.beforeRemoveConnection.emit(e).prevented)return;e.destruct(),this._connections.splice(this.connections.indexOf(e),1),this.events.removeConnection.emit(e),this.connectionEvents.removeTarget(e.events)}}checkConnection(e,n){if(!e||!n)return{connectionAllowed:!1};const s=this.findNodeById(e.nodeId),i=this.findNodeById(n.nodeId);if(s&&i&&s===i)return{connectionAllowed:!1};if(e.isInput&&!n.isInput){const a=e;e=n,n=a}if(e.isInput||!n.isInput)return{connectionAllowed:!1};if(this.connections.some(a=>a.from===e&&a.to===n))return{connectionAllowed:!1};if(this.events.checkConnection.emit({from:e,to:n}).prevented)return{connectionAllowed:!1};const r=this.hooks.checkConnection.execute({from:e,to:n});if(r.some(a=>!a.connectionAllowed))return{connectionAllowed:!1};const o=Array.from(new Set(r.flatMap(a=>a.connectionsInDanger)));return{connectionAllowed:!0,dummyConnection:new HO(e,n),connectionsInDanger:o}}findNodeInterface(e){for(const n of this.nodes){for(const s in n.inputs){const i=n.inputs[s];if(i.id===e)return i}for(const s in n.outputs){const i=n.outputs[s];if(i.id===e)return i}}}findNodeById(e){return this.nodes.find(n=>n.id===e)}load(e){try{this._loading=!0;const n=[];for(let s=this.connections.length-1;s>=0;s--)this.removeConnection(this.connections[s]);for(let s=this.nodes.length-1;s>=0;s--)this.removeNode(this.nodes[s]);this.id=e.id;for(const s of e.nodes){const i=this.editor.nodeTypes.get(s.type);if(!i){n.push(`Node type ${s.type} is not registered`);continue}const r=new i.type;this.addNode(r),r.load(s)}for(const s of e.connections){const i=this.findNodeInterface(s.from),r=this.findNodeInterface(s.to);if(i)if(r){const o=new Z1(i,r);o.id=s.id,this.internalAddConnection(o)}else{n.push(`Could not find interface with id ${s.to}`);continue}else{n.push(`Could not find interface with id ${s.from}`);continue}}return this.hooks.load.execute(e),n}finally{this._loading=!1}}save(){const e={id:this.id,nodes:this.nodes.map(n=>n.save()),connections:this.connections.map(n=>({id:n.id,from:n.from.id,to:n.to.id})),inputs:this.inputs,outputs:this.outputs};return this.hooks.save.execute(e)}destroy(){this._destroying=!0;for(const e of this.nodes)this.removeNode(e);this.editor.unregisterGraph(this)}internalAddConnection(e){this.connectionEvents.addTarget(e.events),this._connections.push(e),this.events.addConnection.emit(e)}}const Gl="__baklava_GraphNode-";function Ea(t){return Gl+t.id}function ZDt(t){return class extends qO{constructor(){super(...arguments),this.type=Ea(t),this.inputs={},this.outputs={},this.template=t,this.calculate=async(n,s)=>{var i;if(!this.subgraph)throw new Error(`GraphNode ${this.id}: calculate called without subgraph being initialized`);if(!s.engine||typeof s.engine!="object")throw new Error(`GraphNode ${this.id}: calculate called but no engine provided in context`);const r=s.engine.getInputValues(this.subgraph);for(const c of this.subgraph.inputs)r.set(c.nodeInterfaceId,n[c.id]);const o=await s.engine.runGraph(this.subgraph,r,s.globalValues),a={};for(const c of this.subgraph.outputs)a[c.id]=(i=o.get(c.nodeId))===null||i===void 0?void 0:i.get("output");return a._calculationResults=o,a}}get title(){return this._title}set title(n){this.template.name=n}load(n){if(!this.subgraph)throw new Error("Cannot load a graph node without a graph");if(!this.template)throw new Error("Unable to load graph node without graph template");this.subgraph.load(n.graphState),super.load(n)}save(){if(!this.subgraph)throw new Error("Cannot save a graph node without a graph");return{...super.save(),graphState:this.subgraph.save()}}onPlaced(){this.template.events.updated.subscribe(this,()=>this.initialize()),this.template.events.nameChanged.subscribe(this,n=>{this._title=n}),this.initialize()}onDestroy(){var n;this.template.events.updated.unsubscribe(this),this.template.events.nameChanged.unsubscribe(this),(n=this.subgraph)===null||n===void 0||n.destroy()}initialize(){this.subgraph&&this.subgraph.destroy(),this.subgraph=this.template.createGraph(),this._title=this.template.name,this.updateInterfaces(),this.events.update.emit(null)}updateInterfaces(){if(!this.subgraph)throw new Error("Trying to update interfaces without graph instance");for(const n of this.subgraph.inputs)n.id in this.inputs?this.inputs[n.id].name=n.name:this.addInput(n.id,new Xt(n.name,void 0));for(const n of Object.keys(this.inputs))this.subgraph.inputs.some(s=>s.id===n)||this.removeInput(n);for(const n of this.subgraph.outputs)n.id in this.outputs?this.outputs[n.id].name=n.name:this.addOutput(n.id,new Xt(n.name,void 0));for(const n of Object.keys(this.outputs))this.subgraph.outputs.some(s=>s.id===n)||this.removeOutput(n);this.addOutput("_calculationResults",new Xt("_calculationResults",void 0).setHidden(!0))}}}class Wu{static fromGraph(e,n){return new Wu(e.save(),n)}get name(){return this._name}set name(e){this._name=e,this.events.nameChanged.emit(e);const n=this.editor.nodeTypes.get(Ea(this));n&&(n.title=e)}get inputs(){return this.nodes.filter(n=>n.type===ga).map(n=>({id:n.graphInterfaceId,name:n.inputs.name.value,nodeId:n.id,nodeInterfaceId:n.outputs.placeholder.id}))}get outputs(){return this.nodes.filter(n=>n.type===ba).map(n=>({id:n.graphInterfaceId,name:n.inputs.name.value,nodeId:n.id,nodeInterfaceId:n.outputs.output.id}))}constructor(e,n){this.id=Ri(),this._name="Subgraph",this.events={nameChanged:new Ht(this),updated:new Ht(this)},this.hooks={beforeLoad:new ts(this),afterSave:new ts(this)},this.editor=n,e.id&&(this.id=e.id),e.name&&(this._name=e.name),this.update(e)}update(e){this.nodes=e.nodes,this.connections=e.connections,this.events.updated.emit()}save(){return{id:this.id,name:this.name,nodes:this.nodes,connections:this.connections,inputs:this.inputs,outputs:this.outputs}}createGraph(e){const n=new Map,s=f=>{const m=Ri();return n.set(f,m),m},i=f=>{const m=n.get(f);if(!m)throw new Error(`Unable to create graph from template: Could not map old id ${f} to new id`);return m},r=f=>Wg(f,m=>({id:s(m.id),templateId:m.id,value:m.value})),o=this.nodes.map(f=>({...f,id:s(f.id),inputs:r(f.inputs),outputs:r(f.outputs)})),a=this.connections.map(f=>({id:s(f.id),from:i(f.from),to:i(f.to)})),c=this.inputs.map(f=>({id:f.id,name:f.name,nodeId:i(f.nodeId),nodeInterfaceId:i(f.nodeInterfaceId)})),u=this.outputs.map(f=>({id:f.id,name:f.name,nodeId:i(f.nodeId),nodeInterfaceId:i(f.nodeInterfaceId)})),d={id:Ri(),nodes:o,connections:a,inputs:c,outputs:u};return e||(e=new ec(this.editor)),e.load(d).forEach(f=>console.warn(f)),e.template=this,e}}class JDt{get nodeTypes(){return this._nodeTypes}get graph(){return this._graph}get graphTemplates(){return this._graphTemplates}get graphs(){return this._graphs}get loading(){return this._loading}constructor(){this.events={loaded:new Ht(this),beforeRegisterNodeType:new In(this),registerNodeType:new Ht(this),beforeUnregisterNodeType:new In(this),unregisterNodeType:new Ht(this),beforeAddGraphTemplate:new In(this),addGraphTemplate:new Ht(this),beforeRemoveGraphTemplate:new In(this),removeGraphTemplate:new Ht(this),registerGraph:new Ht(this),unregisterGraph:new Ht(this)},this.hooks={save:new ts(this),load:new ts(this)},this.graphTemplateEvents=Vs(),this.graphTemplateHooks=Vs(),this.graphEvents=Vs(),this.graphHooks=Vs(),this.nodeEvents=Vs(),this.nodeHooks=Vs(),this.connectionEvents=Vs(),this._graphs=new Set,this._nodeTypes=new Map,this._graph=new ec(this),this._graphTemplates=[],this._loading=!1,this.registerNodeType(WO),this.registerNodeType(KO)}registerNodeType(e,n){var s,i;if(this.events.beforeRegisterNodeType.emit({type:e,options:n}).prevented)return;const r=new e;this._nodeTypes.set(r.type,{type:e,category:(s=n==null?void 0:n.category)!==null&&s!==void 0?s:"default",title:(i=n==null?void 0:n.title)!==null&&i!==void 0?i:r.title}),this.events.registerNodeType.emit({type:e,options:n})}unregisterNodeType(e){const n=typeof e=="string"?e:new e().type;if(this.nodeTypes.has(n)){if(this.events.beforeUnregisterNodeType.emit(n).prevented)return;this._nodeTypes.delete(n),this.events.unregisterNodeType.emit(n)}}addGraphTemplate(e){if(this.events.beforeAddGraphTemplate.emit(e).prevented)return;this._graphTemplates.push(e),this.graphTemplateEvents.addTarget(e.events),this.graphTemplateHooks.addTarget(e.hooks);const n=ZDt(e);this.registerNodeType(n,{category:"Subgraphs",title:e.name}),this.events.addGraphTemplate.emit(e)}removeGraphTemplate(e){if(this.graphTemplates.includes(e)){if(this.events.beforeRemoveGraphTemplate.emit(e).prevented)return;const n=Ea(e);for(const s of[this.graph,...this.graphs.values()]){const i=s.nodes.filter(r=>r.type===n);for(const r of i)s.removeNode(r)}this.unregisterNodeType(n),this._graphTemplates.splice(this._graphTemplates.indexOf(e),1),this.graphTemplateEvents.removeTarget(e.events),this.graphTemplateHooks.removeTarget(e.hooks),this.events.removeGraphTemplate.emit(e)}}registerGraph(e){this.graphEvents.addTarget(e.events),this.graphHooks.addTarget(e.hooks),this.nodeEvents.addTarget(e.nodeEvents),this.nodeHooks.addTarget(e.nodeHooks),this.connectionEvents.addTarget(e.connectionEvents),this.events.registerGraph.emit(e),this._graphs.add(e)}unregisterGraph(e){this.graphEvents.removeTarget(e.events),this.graphHooks.removeTarget(e.hooks),this.nodeEvents.removeTarget(e.nodeEvents),this.nodeHooks.removeTarget(e.nodeHooks),this.connectionEvents.removeTarget(e.connectionEvents),this.events.unregisterGraph.emit(e),this._graphs.delete(e)}load(e){try{this._loading=!0,e=this.hooks.load.execute(e),e.graphTemplates.forEach(s=>{const i=new Wu(s,this);this.addGraphTemplate(i)});const n=this._graph.load(e.graph);return this.events.loaded.emit(),n.forEach(s=>console.warn(s)),n}finally{this._loading=!1}}save(){const e={graph:this.graph.save(),graphTemplates:this.graphTemplates.map(n=>n.save())};return this.hooks.save.execute(e)}}function ekt(t,e){const n=new Map;e.graphs.forEach(s=>{s.nodes.forEach(i=>n.set(i.id,i))}),t.forEach((s,i)=>{const r=n.get(i);r&&s.forEach((o,a)=>{const c=r.outputs[a];c&&(c.value=o)})})}class jO extends Error{constructor(){super("Cycle detected")}}function tkt(t){return typeof t=="string"}function QO(t,e){const n=new Map,s=new Map,i=new Map;let r,o;if(t instanceof ec)r=t.nodes,o=t.connections;else{if(!e)throw new Error("Invalid argument value: expected array of connections");r=t,o=e}r.forEach(u=>{Object.values(u.inputs).forEach(d=>n.set(d.id,u.id)),Object.values(u.outputs).forEach(d=>n.set(d.id,u.id))}),r.forEach(u=>{const d=o.filter(f=>f.from&&n.get(f.from.id)===u.id),h=new Set(d.map(f=>n.get(f.to.id)).filter(tkt));s.set(u.id,h),i.set(u,d)});const a=r.slice();o.forEach(u=>{const d=a.findIndex(h=>n.get(u.to.id)===h.id);d>=0&&a.splice(d,1)});const c=[];for(;a.length>0;){const u=a.pop();c.push(u);const d=s.get(u.id);for(;d.size>0;){const h=d.values().next().value;if(d.delete(h),Array.from(s.values()).every(f=>!f.has(h))){const f=r.find(m=>m.id===h);a.push(f)}}}if(Array.from(s.values()).some(u=>u.size>0))throw new jO;return{calculationOrder:c,connectionsFromNode:i,interfaceIdToNodeId:n}}function nkt(t,e){try{return QO(t,e),!1}catch(n){if(n instanceof jO)return!0;throw n}}var Vn;(function(t){t.Running="Running",t.Idle="Idle",t.Paused="Paused",t.Stopped="Stopped"})(Vn||(Vn={}));class skt{get status(){return this.isRunning?Vn.Running:this.internalStatus}constructor(e){this.editor=e,this.events={beforeRun:new In(this),afterRun:new Ht(this),statusChange:new Ht(this),beforeNodeCalculation:new Ht(this),afterNodeCalculation:new Ht(this)},this.hooks={gatherCalculationData:new ts(this),transferData:new zO},this.recalculateOrder=!0,this.internalStatus=Vn.Stopped,this.isRunning=!1,this.editor.nodeEvents.update.subscribe(this,(n,s)=>{s.graph&&!s.graph.loading&&s.graph.activeTransactions===0&&this.internalOnChange(s,n??void 0)}),this.editor.graphEvents.addNode.subscribe(this,(n,s)=>{this.recalculateOrder=!0,!s.loading&&s.activeTransactions===0&&this.internalOnChange()}),this.editor.graphEvents.removeNode.subscribe(this,(n,s)=>{this.recalculateOrder=!0,!s.loading&&s.activeTransactions===0&&this.internalOnChange()}),this.editor.graphEvents.addConnection.subscribe(this,(n,s)=>{this.recalculateOrder=!0,!s.loading&&s.activeTransactions===0&&this.internalOnChange()}),this.editor.graphEvents.removeConnection.subscribe(this,(n,s)=>{this.recalculateOrder=!0,!s.loading&&s.activeTransactions===0&&this.internalOnChange()}),this.editor.graphHooks.checkConnection.subscribe(this,n=>this.checkConnection(n.from,n.to))}start(){this.internalStatus===Vn.Stopped&&(this.internalStatus=Vn.Idle,this.events.statusChange.emit(this.status))}pause(){this.internalStatus===Vn.Idle&&(this.internalStatus=Vn.Paused,this.events.statusChange.emit(this.status))}resume(){this.internalStatus===Vn.Paused&&(this.internalStatus=Vn.Idle,this.events.statusChange.emit(this.status))}stop(){(this.internalStatus===Vn.Idle||this.internalStatus===Vn.Paused)&&(this.internalStatus=Vn.Stopped,this.events.statusChange.emit(this.status))}async runOnce(e,...n){if(this.events.beforeRun.emit(e).prevented)return null;try{this.isRunning=!0,this.events.statusChange.emit(this.status),this.recalculateOrder&&this.calculateOrder();const s=await this.execute(e,...n);return this.events.afterRun.emit(s),s}finally{this.isRunning=!1,this.events.statusChange.emit(this.status)}}checkConnection(e,n){if(e.templateId){const r=this.findInterfaceByTemplateId(this.editor.graph.nodes,e.templateId);if(!r)return{connectionAllowed:!0,connectionsInDanger:[]};e=r}if(n.templateId){const r=this.findInterfaceByTemplateId(this.editor.graph.nodes,n.templateId);if(!r)return{connectionAllowed:!0,connectionsInDanger:[]};n=r}const s=new HO(e,n);let i=this.editor.graph.connections.slice();return n.allowMultipleConnections||(i=i.filter(r=>r.to!==n)),i.push(s),nkt(this.editor.graph.nodes,i)?{connectionAllowed:!1,connectionsInDanger:[]}:{connectionAllowed:!0,connectionsInDanger:n.allowMultipleConnections?[]:this.editor.graph.connections.filter(r=>r.to===n)}}calculateOrder(){this.recalculateOrder=!0}async calculateWithoutData(...e){const n=this.hooks.gatherCalculationData.execute(void 0);return await this.runOnce(n,...e)}validateNodeCalculationOutput(e,n){if(typeof n!="object")throw new Error(`Invalid calculation return value from node ${e.id} (type ${e.type})`);Object.keys(e.outputs).forEach(s=>{if(!(s in n))throw new Error(`Calculation return value from node ${e.id} (type ${e.type}) is missing key "${s}"`)})}internalOnChange(e,n){this.internalStatus===Vn.Idle&&this.onChange(this.recalculateOrder,e,n)}findInterfaceByTemplateId(e,n){for(const s of e)for(const i of[...Object.values(s.inputs),...Object.values(s.outputs)])if(i.templateId===n)return i;return null}}class ikt extends skt{constructor(e){super(e),this.order=new Map}start(){super.start(),this.recalculateOrder=!0,this.calculateWithoutData()}async runGraph(e,n,s){this.order.has(e.id)||this.order.set(e.id,QO(e));const{calculationOrder:i,connectionsFromNode:r}=this.order.get(e.id),o=new Map;for(const a of i){const c={};Object.entries(a.inputs).forEach(([d,h])=>{c[d]=this.getInterfaceValue(n,h.id)}),this.events.beforeNodeCalculation.emit({inputValues:c,node:a});let u;if(a.calculate)u=await a.calculate(c,{globalValues:s,engine:this});else{u={};for(const[d,h]of Object.entries(a.outputs))u[d]=this.getInterfaceValue(n,h.id)}this.validateNodeCalculationOutput(a,u),this.events.afterNodeCalculation.emit({outputValues:u,node:a}),o.set(a.id,new Map(Object.entries(u))),r.has(a)&&r.get(a).forEach(d=>{var h;const f=(h=Object.entries(a.outputs).find(([,_])=>_.id===d.from.id))===null||h===void 0?void 0:h[0];if(!f)throw new Error(`Could not find key for interface ${d.from.id} This is likely a Baklava internal issue. Please report it on GitHub.`);const m=this.hooks.transferData.execute(u[f],d);d.to.allowMultipleConnections?n.has(d.to.id)?n.get(d.to.id).push(m):n.set(d.to.id,[m]):n.set(d.to.id,m)})}return o}async execute(e){this.recalculateOrder&&(this.order.clear(),this.recalculateOrder=!1);const n=this.getInputValues(this.editor.graph);return await this.runGraph(this.editor.graph,n,e)}getInputValues(e){const n=new Map;for(const s of e.nodes)Object.values(s.inputs).forEach(i=>{i.connectionCount===0&&n.set(i.id,i.value)}),s.calculate||Object.values(s.outputs).forEach(i=>{n.set(i.id,i.value)});return n}onChange(e){this.recalculateOrder=e||this.recalculateOrder,this.calculateWithoutData()}getInterfaceValue(e,n){if(!e.has(n))throw new Error(`Could not find value for interface ${n} -This is likely a Baklava internal issue. Please report it on GitHub.`);return e.get(n)}}let Kg=null;function rkt(t){Kg=t}function vs(){if(!Kg)throw new Error("providePlugin() must be called before usePlugin()");return{viewModel:Kg}}function Bs(){const{viewModel:t}=vs();return{graph:xd(t.value,"displayedGraph"),switchGraph:t.value.switchGraph}}function XO(t){const{graph:e}=Bs(),n=lt(null),s=lt(null);return{dragging:et(()=>!!n.value),onPointerDown:c=>{n.value={x:c.pageX,y:c.pageY},s.value={x:t.value.x,y:t.value.y}},onPointerMove:c=>{if(n.value){const u=c.pageX-n.value.x,d=c.pageY-n.value.y;t.value.x=s.value.x+u/e.value.scaling,t.value.y=s.value.y+d/e.value.scaling}},onPointerUp:()=>{n.value=null,s.value=null}}}function ZO(t,e,n){if(!e.template)return!1;if(Ea(e.template)===n)return!0;const s=t.graphTemplates.find(r=>Ea(r)===n);return s?s.nodes.filter(r=>r.type.startsWith(Gl)).some(r=>ZO(t,e,r.type)):!1}function JO(t){return et(()=>{const e=Array.from(t.value.editor.nodeTypes.entries()),n=new Set(e.map(([,i])=>i.category)),s=[];for(const i of n.values()){let r=e.filter(([,o])=>o.category===i);t.value.displayedGraph.template?r=r.filter(([o])=>!ZO(t.value.editor,t.value.displayedGraph,o)):r=r.filter(([o])=>![ga,ba].includes(o)),r.length>0&&s.push({name:i,nodeTypes:Object.fromEntries(r)})}return s.sort((i,r)=>i.name==="default"?-1:r.name==="default"||i.name>r.name?1:-1),s})}function eI(){const{graph:t}=Bs();return{transform:(n,s)=>{const i=n/t.value.scaling-t.value.panning.x,r=s/t.value.scaling-t.value.panning.y;return[i,r]}}}function okt(){const{graph:t}=Bs();let e=[],n=-1,s={x:0,y:0};const i=et(()=>t.value.panning),r=XO(i),o=et(()=>({"transform-origin":"0 0",transform:`scale(${t.value.scaling}) translate(${t.value.panning.x}px, ${t.value.panning.y}px)`})),a=(m,_,E)=>{const b=[m/t.value.scaling-t.value.panning.x,_/t.value.scaling-t.value.panning.y],g=[m/E-t.value.panning.x,_/E-t.value.panning.y],y=[g[0]-b[0],g[1]-b[1]];t.value.panning.x+=y[0],t.value.panning.y+=y[1],t.value.scaling=E},c=m=>{m.preventDefault();let _=m.deltaY;m.deltaMode===1&&(_*=32);const E=t.value.scaling*(1-_/3e3);a(m.offsetX,m.offsetY,E)},u=()=>({ax:e[0].clientX,ay:e[0].clientY,bx:e[1].clientX,by:e[1].clientY});return{styles:o,...r,onPointerDown:m=>{if(e.push(m),r.onPointerDown(m),e.length===2){const{ax:_,ay:E,bx:b,by:g}=u();s={x:_+(b-_)/2,y:E+(g-E)/2}}},onPointerMove:m=>{for(let _=0;_0){const R=t.value.scaling*(1+(S-n)/500);a(s.x,s.y,R)}n=S}else r.onPointerMove(m)},onPointerUp:m=>{e=e.filter(_=>_.pointerId!==m.pointerId),n=-1,r.onPointerUp()},onMouseWheel:c}}var us=(t=>(t[t.NONE=0]="NONE",t[t.ALLOWED=1]="ALLOWED",t[t.FORBIDDEN=2]="FORBIDDEN",t))(us||{});const tI=Symbol();function akt(){const{graph:t}=Bs(),e=lt(null),n=lt(null),s=a=>{e.value&&(e.value.mx=a.offsetX/t.value.scaling-t.value.panning.x,e.value.my=a.offsetY/t.value.scaling-t.value.panning.y)},i=()=>{if(n.value){if(e.value)return;const a=t.value.connections.find(c=>c.to===n.value);n.value.isInput&&a?(e.value={status:us.NONE,from:a.from},t.value.removeConnection(a)):e.value={status:us.NONE,from:n.value},e.value.mx=void 0,e.value.my=void 0}},r=()=>{if(e.value&&n.value){if(e.value.from===n.value)return;t.value.addConnection(e.value.from,e.value.to)}e.value=null},o=a=>{if(n.value=a??null,a&&e.value){e.value.to=a;const c=t.value.checkConnection(e.value.from,e.value.to);if(e.value.status=c.connectionAllowed?us.ALLOWED:us.FORBIDDEN,c.connectionAllowed){const u=c.connectionsInDanger.map(d=>d.id);t.value.connections.forEach(d=>{u.includes(d.id)&&(d.isInDanger=!0)})}}else!a&&e.value&&(e.value.to=void 0,e.value.status=us.NONE,t.value.connections.forEach(c=>{c.isInDanger=!1}))};return zo(tI,{temporaryConnection:e,hoveredOver:o}),{temporaryConnection:e,onMouseMove:s,onMouseDown:i,onMouseUp:r,hoveredOver:o}}function lkt(t){const e=lt(!1),n=lt(0),s=lt(0),i=JO(t),{transform:r}=eI(),o=et(()=>{let d=[];const h={};for(const m of i.value){const _=Object.entries(m.nodeTypes).map(([E,b])=>({label:b.title,value:"addNode:"+E}));m.name==="default"?d=_:h[m.name]=_}const f=[...Object.entries(h).map(([m,_])=>({label:m,submenu:_}))];return f.length>0&&d.length>0&&f.push({isDivider:!0}),f.push(...d),f}),a=et(()=>t.value.settings.contextMenu.additionalItems.length===0?o.value:[{label:"Add node",submenu:o.value},...t.value.settings.contextMenu.additionalItems.map(d=>"isDivider"in d||"submenu"in d?d:{label:d.label,value:"command:"+d.command,disabled:!t.value.commandHandler.canExecuteCommand(d.command)})]);function c(d){e.value=!0,n.value=d.offsetX,s.value=d.offsetY}function u(d){if(d.startsWith("addNode:")){const h=d.substring(8),f=t.value.editor.nodeTypes.get(h);if(!f)return;const m=Wn(new f.type);t.value.displayedGraph.addNode(m);const[_,E]=r(n.value,s.value);m.position.x=_,m.position.y=E}else if(d.startsWith("command:")){const h=d.substring(8);t.value.commandHandler.canExecuteCommand(h)&&t.value.commandHandler.executeCommand(h)}}return{show:e,x:n,y:s,items:a,open:c,onClick:u}}const ckt=cn({setup(){const{viewModel:t}=vs(),{graph:e}=Bs();return{styles:et(()=>{const s=t.value.settings.background,i=e.value.panning.x*e.value.scaling,r=e.value.panning.y*e.value.scaling,o=e.value.scaling*s.gridSize,a=o/s.gridDivision,c=`${o}px ${o}px, ${o}px ${o}px`,u=e.value.scaling>s.subGridVisibleThreshold?`, ${a}px ${a}px, ${a}px ${a}px`:"";return{backgroundPosition:`left ${i}px top ${r}px`,backgroundSize:`${c} ${u}`}})}}}),dn=(t,e)=>{const n=t.__vccOpts||t;for(const[s,i]of e)n[s]=i;return n};function dkt(t,e,n,s,i,r){return T(),w("div",{class:"background",style:$t(t.styles)},null,4)}const ukt=dn(ckt,[["render",dkt]]);function pkt(t){return mw()?(VI(t),!0):!1}function GE(t){return typeof t=="function"?t():Ct(t)}const nI=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const _kt=Object.prototype.toString,hkt=t=>_kt.call(t)==="[object Object]",Ed=()=>{},fkt=mkt();function mkt(){var t,e;return nI&&((t=window==null?void 0:window.navigator)==null?void 0:t.userAgent)&&(/iP(ad|hone|od)/.test(window.navigator.userAgent)||((e=window==null?void 0:window.navigator)==null?void 0:e.maxTouchPoints)>2&&/iPad|Macintosh/.test(window==null?void 0:window.navigator.userAgent))}function gkt(t,e,n=!1){return e.reduce((s,i)=>(i in t&&(!n||t[i]!==void 0)&&(s[i]=t[i]),s),{})}function bkt(t,e={}){if(!un(t))return SM(t);const n=Array.isArray(t.value)?Array.from({length:t.value.length}):{};for(const s in t.value)n[s]=vM(()=>({get(){return t.value[s]},set(i){var r;if((r=GE(e.replaceRef))!=null?r:!0)if(Array.isArray(t.value)){const a=[...t.value];a[s]=i,t.value=a}else{const a={...t.value,[s]:i};Object.setPrototypeOf(a,Object.getPrototypeOf(t.value)),t.value=a}else t.value[s]=i}}));return n}function al(t){var e;const n=GE(t);return(e=n==null?void 0:n.$el)!=null?e:n}const VE=nI?window:void 0;function yl(...t){let e,n,s,i;if(typeof t[0]=="string"||Array.isArray(t[0])?([n,s,i]=t,e=VE):[e,n,s,i]=t,!e)return Ed;Array.isArray(n)||(n=[n]),Array.isArray(s)||(s=[s]);const r=[],o=()=>{r.forEach(d=>d()),r.length=0},a=(d,h,f,m)=>(d.addEventListener(h,f,m),()=>d.removeEventListener(h,f,m)),c=Mn(()=>[al(e),GE(i)],([d,h])=>{if(o(),!d)return;const f=hkt(h)?{...h}:h;r.push(...n.flatMap(m=>s.map(_=>a(d,m,_,f))))},{immediate:!0,flush:"post"}),u=()=>{c(),o()};return pkt(u),u}let J1=!1;function sI(t,e,n={}){const{window:s=VE,ignore:i=[],capture:r=!0,detectIframe:o=!1}=n;if(!s)return Ed;fkt&&!J1&&(J1=!0,Array.from(s.document.body.children).forEach(f=>f.addEventListener("click",Ed)),s.document.documentElement.addEventListener("click",Ed));let a=!0;const c=f=>i.some(m=>{if(typeof m=="string")return Array.from(s.document.querySelectorAll(m)).some(_=>_===f.target||f.composedPath().includes(_));{const _=al(m);return _&&(f.target===_||f.composedPath().includes(_))}}),d=[yl(s,"click",f=>{const m=al(t);if(!(!m||m===f.target||f.composedPath().includes(m))){if(f.detail===0&&(a=!c(f)),!a){a=!0;return}e(f)}},{passive:!0,capture:r}),yl(s,"pointerdown",f=>{const m=al(t);a=!c(f)&&!!(m&&!f.composedPath().includes(m))},{passive:!0}),o&&yl(s,"blur",f=>{setTimeout(()=>{var m;const _=al(t);((m=s.document.activeElement)==null?void 0:m.tagName)==="IFRAME"&&!(_!=null&&_.contains(s.document.activeElement))&&e(f)},0)})].filter(Boolean);return()=>d.forEach(f=>f())}const iI={x:0,y:0,pointerId:0,pressure:0,tiltX:0,tiltY:0,width:0,height:0,twist:0,pointerType:null},Ekt=Object.keys(iI);function ykt(t={}){const{target:e=VE}=t,n=lt(!1),s=lt(t.initialValue||{});Object.assign(s.value,iI,s.value);const i=r=>{n.value=!0,!(t.pointerTypes&&!t.pointerTypes.includes(r.pointerType))&&(s.value=gkt(r,Ekt,!1))};if(e){const r={passive:!0};yl(e,["pointerdown","pointermove","pointerup"],i,r),yl(e,"pointerleave",()=>n.value=!1,r)}return{...bkt(s),isInside:n}}const vkt=["onMouseenter","onMouseleave","onClick"],Skt={class:"flex-fill"},Tkt={key:0,class:"__submenu-icon",style:{"line-height":"1em"}},xkt=l("svg",{width:"13",height:"13",viewBox:"-60 120 250 250"},[l("path",{d:"M160.875 279.5625 L70.875 369.5625 L70.875 189.5625 L160.875 279.5625 Z",stroke:"none",fill:"white"})],-1),Ckt=[xkt],zE=cn({__name:"ContextMenu",props:{modelValue:{type:Boolean},items:{},x:{default:0},y:{default:0},isNested:{type:Boolean,default:!1},isFlipped:{default:()=>({x:!1,y:!1})},flippable:{type:Boolean,default:!1}},emits:["update:modelValue","click"],setup(t,{emit:e}){const n=t,s=e;let i=null;const r=lt(null),o=lt(-1),a=lt(0),c=lt({x:!1,y:!1}),u=et(()=>n.flippable&&(c.value.x||n.isFlipped.x)),d=et(()=>n.flippable&&(c.value.y||n.isFlipped.y)),h=et(()=>{const y={};return n.isNested||(y.top=(d.value?n.y-a.value:n.y)+"px",y.left=n.x+"px"),y}),f=et(()=>({"--flipped-x":u.value,"--flipped-y":d.value,"--nested":n.isNested})),m=et(()=>n.items.map(y=>({...y,hover:!1})));Mn([()=>n.y,()=>n.items],()=>{var y,v,S,R;a.value=n.items.length*30;const C=((v=(y=r.value)==null?void 0:y.parentElement)==null?void 0:v.offsetWidth)??0,A=((R=(S=r.value)==null?void 0:S.parentElement)==null?void 0:R.offsetHeight)??0;c.value.x=!n.isNested&&n.x>C*.75,c.value.y=!n.isNested&&n.y+a.value>A-20}),sI(r,()=>{n.modelValue&&s("update:modelValue",!1)});const _=y=>{!y.submenu&&y.value&&(s("click",y.value),s("update:modelValue",!1))},E=y=>{s("click",y),o.value=-1,n.isNested||s("update:modelValue",!1)},b=(y,v)=>{n.items[v].submenu&&(o.value=v,i!==null&&(clearTimeout(i),i=null))},g=(y,v)=>{n.items[v].submenu&&(i=window.setTimeout(()=>{o.value=-1,i=null},200))};return(y,v)=>{const S=at("ContextMenu",!0);return T(),wt(Ds,{name:"slide-fade"},{default:We(()=>[U(l("div",{ref_key:"el",ref:r,class:Fe(["baklava-context-menu",f.value]),style:$t(h.value)},[(T(!0),w(Ve,null,Ze(m.value,(R,C)=>(T(),w(Ve,null,[R.isDivider?(T(),w("div",{key:`d-${C}`,class:"divider"})):(T(),w("div",{key:`i-${C}`,class:Fe(["item",{submenu:!!R.submenu,"--disabled":!!R.disabled}]),onMouseenter:A=>b(A,C),onMouseleave:A=>g(A,C),onClick:ae(A=>_(R),["stop","prevent"])},[l("div",Skt,X(R.label),1),R.submenu?(T(),w("div",Tkt,Ckt)):G("",!0),R.submenu?(T(),wt(S,{key:1,"model-value":o.value===C,items:R.submenu,"is-nested":!0,"is-flipped":{x:u.value,y:d.value},flippable:y.flippable,onClick:E},null,8,["model-value","items","is-flipped","flippable"])):G("",!0)],42,vkt))],64))),256))],6),[[xt,y.modelValue]])]),_:1})}}}),wkt={},Rkt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"16",height:"16",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},Akt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),Nkt=l("circle",{cx:"12",cy:"12",r:"1"},null,-1),Okt=l("circle",{cx:"12",cy:"19",r:"1"},null,-1),Ikt=l("circle",{cx:"12",cy:"5",r:"1"},null,-1),Mkt=[Akt,Nkt,Okt,Ikt];function Dkt(t,e){return T(),w("svg",Rkt,Mkt)}const rI=dn(wkt,[["render",Dkt]]),kkt=["id"],Lkt={key:0,class:"__tooltip"},Pkt={key:2,class:"align-middle"},ew=cn({__name:"NodeInterface",props:{node:{},intf:{}},setup(t){const e=(b,g=100)=>{const y=b!=null&&b.toString?b.toString():"";return y.length>g?y.slice(0,g)+"...":y},n=t,{viewModel:s}=vs(),{hoveredOver:i,temporaryConnection:r}=Zn(tI),o=lt(null),a=et(()=>n.intf.connectionCount>0),c=lt(!1),u=et(()=>s.value.settings.displayValueOnHover&&c.value),d=et(()=>({"--input":n.intf.isInput,"--output":!n.intf.isInput,"--connected":a.value})),h=et(()=>n.intf.component&&(!n.intf.isInput||!n.intf.port||n.intf.connectionCount===0)),f=()=>{c.value=!0,i(n.intf)},m=()=>{c.value=!1,i(void 0)},_=()=>{o.value&&s.value.hooks.renderInterface.execute({intf:n.intf,el:o.value})},E=()=>{const b=s.value.displayedGraph.sidebar;b.nodeId=n.node.id,b.optionName=n.intf.name,b.visible=!0};return si(_),Hl(_),(b,g)=>{var y;return T(),w("div",{id:b.intf.id,ref_key:"el",ref:o,class:Fe(["baklava-node-interface",d.value])},[b.intf.port?(T(),w("div",{key:0,class:Fe(["__port",{"--selected":((y=Ct(r))==null?void 0:y.from)===b.intf}]),onPointerover:f,onPointerout:m},[An(b.$slots,"portTooltip",{showTooltip:u.value},()=>[u.value===!0?(T(),w("span",Lkt,X(e(b.intf.value)),1)):G("",!0)])],34)):G("",!0),h.value?(T(),wt(pu(b.intf.component),{key:1,modelValue:b.intf.value,"onUpdate:modelValue":g[0]||(g[0]=v=>b.intf.value=v),node:b.node,intf:b.intf,onOpenSidebar:E},null,40,["modelValue","node","intf"])):(T(),w("span",Pkt,X(b.intf.name),1))],10,kkt)}}}),Ukt=["id","data-node-type"],Fkt={class:"__title-label"},Bkt={class:"__menu"},Gkt={class:"__outputs"},Vkt={class:"__inputs"},zkt=cn({__name:"Node",props:{node:{},selected:{type:Boolean,default:!1},dragging:{type:Boolean}},emits:["select","start-drag"],setup(t,{emit:e}){const n=t,s=e,{viewModel:i}=vs(),{graph:r,switchGraph:o}=Bs(),a=lt(null),c=lt(!1),u=lt(""),d=lt(null),h=lt(!1),f=lt(!1),m=et(()=>{const B=[{value:"rename",label:"Rename"},{value:"delete",label:"Delete"}];return n.node.type.startsWith(Gl)&&B.push({value:"editSubgraph",label:"Edit Subgraph"}),B}),_=et(()=>({"--selected":n.selected,"--dragging":n.dragging,"--two-column":!!n.node.twoColumn})),E=et(()=>{var B,z;return{top:`${((B=n.node.position)==null?void 0:B.y)??0}px`,left:`${((z=n.node.position)==null?void 0:z.x)??0}px`,"--width":`${n.node.width??i.value.settings.nodes.defaultWidth}px`}}),b=et(()=>Object.values(n.node.inputs).filter(B=>!B.hidden)),g=et(()=>Object.values(n.node.outputs).filter(B=>!B.hidden)),y=()=>{s("select")},v=B=>{n.selected||y(),s("start-drag",B)},S=()=>{f.value=!0},R=async B=>{var z;switch(B){case"delete":r.value.removeNode(n.node);break;case"rename":u.value=n.node.title,c.value=!0,await Ue(),(z=d.value)==null||z.focus();break;case"editSubgraph":o(n.node.template);break}},C=()=>{n.node.title=u.value,c.value=!1},A=()=>{a.value&&i.value.hooks.renderNode.execute({node:n.node,el:a.value})},D=B=>{h.value=!0,B.preventDefault()},x=B=>{if(!h.value)return;const z=n.node.width+B.movementX/r.value.scaling,J=i.value.settings.nodes.minWidth,M=i.value.settings.nodes.maxWidth;n.node.width=Math.max(J,Math.min(M,z))},O=()=>{h.value=!1};return si(()=>{A(),window.addEventListener("mousemove",x),window.addEventListener("mouseup",O)}),Hl(A),Ca(()=>{window.removeEventListener("mousemove",x),window.removeEventListener("mouseup",O)}),(B,z)=>(T(),w("div",{id:B.node.id,ref_key:"el",ref:a,class:Fe(["baklava-node",_.value]),style:$t(E.value),"data-node-type":B.node.type,onPointerdown:y},[Ct(i).settings.nodes.resizable?(T(),w("div",{key:0,class:"__resize-handle",onMousedown:D},null,32)):G("",!0),An(B.$slots,"title",{},()=>[l("div",{class:"__title",onPointerdown:ae(v,["self","stop"])},[c.value?U((T(),w("input",{key:1,ref_key:"renameInputEl",ref:d,"onUpdate:modelValue":z[1]||(z[1]=J=>u.value=J),type:"text",class:"baklava-input",placeholder:"Node Name",onBlur:C,onKeydown:ei(C,["enter"])},null,544)),[[ue,u.value]]):(T(),w(Ve,{key:0},[l("div",Fkt,X(B.node.title),1),l("div",Bkt,[he(rI,{class:"--clickable",onClick:S}),he(zE,{modelValue:f.value,"onUpdate:modelValue":z[0]||(z[0]=J=>f.value=J),x:0,y:0,items:m.value,onClick:R},null,8,["modelValue","items"])])],64))],32)]),An(B.$slots,"content",{},()=>[l("div",{class:"__content",onKeydown:z[2]||(z[2]=ei(ae(()=>{},["stop"]),["delete"]))},[l("div",Gkt,[(T(!0),w(Ve,null,Ze(g.value,J=>An(B.$slots,"nodeInterface",{key:J.id,type:"output",node:B.node,intf:J},()=>[he(ew,{node:B.node,intf:J},null,8,["node","intf"])])),128))]),l("div",Vkt,[(T(!0),w(Ve,null,Ze(b.value,J=>An(B.$slots,"nodeInterface",{key:J.id,type:"input",node:B.node,intf:J},()=>[he(ew,{node:B.node,intf:J},null,8,["node","intf"])])),128))])],32)])],46,Ukt))}}),Hkt=cn({props:{x1:{type:Number,required:!0},y1:{type:Number,required:!0},x2:{type:Number,required:!0},y2:{type:Number,required:!0},state:{type:Number,default:us.NONE},isTemporary:{type:Boolean,default:!1}},setup(t){const{viewModel:e}=vs(),{graph:n}=Bs(),s=(o,a)=>{const c=(o+n.value.panning.x)*n.value.scaling,u=(a+n.value.panning.y)*n.value.scaling;return[c,u]},i=et(()=>{const[o,a]=s(t.x1,t.y1),[c,u]=s(t.x2,t.y2);if(e.value.settings.useStraightConnections)return`M ${o} ${a} L ${c} ${u}`;{const d=.3*Math.abs(o-c);return`M ${o} ${a} C ${o+d} ${a}, ${c-d} ${u}, ${c} ${u}`}}),r=et(()=>({"--temporary":t.isTemporary,"--allowed":t.state===us.ALLOWED,"--forbidden":t.state===us.FORBIDDEN}));return{d:i,classes:r}}}),qkt=["d"];function Ykt(t,e,n,s,i,r){return T(),w("path",{class:Fe(["baklava-connection",t.classes]),d:t.d},null,10,qkt)}const oI=dn(Hkt,[["render",Ykt]]);function $kt(t){return document.getElementById(t.id)}function ya(t){const e=document.getElementById(t.id),n=e==null?void 0:e.getElementsByClassName("__port");return{node:(e==null?void 0:e.closest(".baklava-node"))??null,interface:e,port:n&&n.length>0?n[0]:null}}const Wkt=cn({components:{"connection-view":oI},props:{connection:{type:Object,required:!0}},setup(t){const{graph:e}=Bs();let n;const s=lt({x1:0,y1:0,x2:0,y2:0}),i=et(()=>t.connection.isInDanger?us.FORBIDDEN:us.NONE),r=et(()=>{var u;return(u=e.value.findNodeById(t.connection.from.nodeId))==null?void 0:u.position}),o=et(()=>{var u;return(u=e.value.findNodeById(t.connection.to.nodeId))==null?void 0:u.position}),a=u=>u.node&&u.interface&&u.port?[u.node.offsetLeft+u.interface.offsetLeft+u.port.offsetLeft+u.port.clientWidth/2,u.node.offsetTop+u.interface.offsetTop+u.port.offsetTop+u.port.clientHeight/2]:[0,0],c=()=>{const u=ya(t.connection.from),d=ya(t.connection.to);u.node&&d.node&&(n||(n=new ResizeObserver(()=>{c()}),n.observe(u.node),n.observe(d.node)));const[h,f]=a(u),[m,_]=a(d);s.value={x1:h,y1:f,x2:m,y2:_}};return si(async()=>{await Ue(),c()}),Ca(()=>{n&&n.disconnect()}),Mn([r,o],()=>c(),{deep:!0}),{d:s,state:i}}});function Kkt(t,e,n,s,i,r){const o=at("connection-view");return T(),wt(o,{x1:t.d.x1,y1:t.d.y1,x2:t.d.x2,y2:t.d.y2,state:t.state},null,8,["x1","y1","x2","y2","state"])}const jkt=dn(Wkt,[["render",Kkt]]);function Zd(t){return t.node&&t.interface&&t.port?[t.node.offsetLeft+t.interface.offsetLeft+t.port.offsetLeft+t.port.clientWidth/2,t.node.offsetTop+t.interface.offsetTop+t.port.offsetTop+t.port.clientHeight/2]:[0,0]}const Qkt=cn({components:{"connection-view":oI},props:{connection:{type:Object,required:!0}},setup(t){const e=et(()=>t.connection?t.connection.status:us.NONE);return{d:et(()=>{if(!t.connection)return{input:[0,0],output:[0,0]};const s=Zd(ya(t.connection.from)),i=t.connection.to?Zd(ya(t.connection.to)):[t.connection.mx||s[0],t.connection.my||s[1]];return t.connection.from.isInput?{input:i,output:s}:{input:s,output:i}}),status:e}}});function Xkt(t,e,n,s,i,r){const o=at("connection-view");return T(),wt(o,{x1:t.d.input[0],y1:t.d.input[1],x2:t.d.output[0],y2:t.d.output[1],state:t.status,"is-temporary":""},null,8,["x1","y1","x2","y2","state"])}const Zkt=dn(Qkt,[["render",Xkt]]),Jkt=cn({setup(){const{viewModel:t}=vs(),{graph:e}=Bs(),n=lt(null),s=xd(t.value.settings.sidebar,"width"),i=et(()=>t.value.settings.sidebar.resizable),r=et(()=>{const h=e.value.sidebar.nodeId;return e.value.nodes.find(f=>f.id===h)}),o=et(()=>({width:`${s.value}px`})),a=et(()=>r.value?[...Object.values(r.value.inputs),...Object.values(r.value.outputs)].filter(f=>f.displayInSidebar&&f.component):[]),c=()=>{e.value.sidebar.visible=!1},u=()=>{window.addEventListener("mousemove",d),window.addEventListener("mouseup",()=>{window.removeEventListener("mousemove",d)},{once:!0})},d=h=>{var f,m;const _=((m=(f=n.value)==null?void 0:f.parentElement)==null?void 0:m.getBoundingClientRect().width)??500;let E=s.value-h.movementX;E<300?E=300:E>.9*_&&(E=.9*_),s.value=E};return{el:n,graph:e,resizable:i,node:r,styles:o,displayedInterfaces:a,startResize:u,close:c}}}),eLt={class:"__header"},tLt={class:"__node-name"};function nLt(t,e,n,s,i,r){return T(),w("div",{ref:"el",class:Fe(["baklava-sidebar",{"--open":t.graph.sidebar.visible}]),style:$t(t.styles)},[t.resizable?(T(),w("div",{key:0,class:"__resizer",onMousedown:e[0]||(e[0]=(...o)=>t.startResize&&t.startResize(...o))},null,32)):G("",!0),l("div",eLt,[l("button",{tabindex:"-1",class:"__close",onClick:e[1]||(e[1]=(...o)=>t.close&&t.close(...o))},"×"),l("div",tLt,[l("b",null,X(t.node?t.node.title:""),1)])]),(T(!0),w(Ve,null,Ze(t.displayedInterfaces,o=>(T(),w("div",{key:o.id,class:"__interface"},[(T(),wt(pu(o.component),{modelValue:o.value,"onUpdate:modelValue":a=>o.value=a,node:t.node,intf:o},null,8,["modelValue","onUpdate:modelValue","node","intf"]))]))),128))],6)}const sLt=dn(Jkt,[["render",nLt]]),iLt=cn({__name:"Minimap",setup(t){const{viewModel:e}=vs(),{graph:n}=Bs(),s=lt(null),i=lt(!1);let r,o=!1,a={x1:0,y1:0,x2:0,y2:0},c;const u=()=>{var C,A;if(!r)return;r.canvas.width=s.value.offsetWidth,r.canvas.height=s.value.offsetHeight;const D=new Map,x=new Map;for(const M of n.value.nodes){const q=$kt(M),H=(q==null?void 0:q.offsetWidth)??0,P=(q==null?void 0:q.offsetHeight)??0,$=((C=M.position)==null?void 0:C.x)??0,ee=((A=M.position)==null?void 0:A.y)??0;D.set(M,{x1:$,y1:ee,x2:$+H,y2:ee+P}),x.set(M,q)}const O={x1:Number.MAX_SAFE_INTEGER,y1:Number.MAX_SAFE_INTEGER,x2:Number.MIN_SAFE_INTEGER,y2:Number.MIN_SAFE_INTEGER};for(const M of D.values())M.x1O.x2&&(O.x2=M.x2),M.y2>O.y2&&(O.y2=M.y2);const B=50;O.x1-=B,O.y1-=B,O.x2+=B,O.y2+=B,a=O;const z=r.canvas.width/r.canvas.height,J=(a.x2-a.x1)/(a.y2-a.y1);if(z>J){const M=(z-J)*(a.y2-a.y1)*.5;a.x1-=M,a.x2+=M}else{const M=a.x2-a.x1,q=a.y2-a.y1,H=(M-z*q)/z*.5;a.y1-=H,a.y2+=H}r.clearRect(0,0,r.canvas.width,r.canvas.height),r.strokeStyle="white";for(const M of n.value.connections){const[q,H]=Zd(ya(M.from)),[P,$]=Zd(ya(M.to)),[ee,re]=d(q,H),[me,Se]=d(P,$);if(r.beginPath(),r.moveTo(ee,re),e.value.settings.useStraightConnections)r.lineTo(me,Se);else{const le=.3*Math.abs(ee-me);r.bezierCurveTo(ee+le,re,me-le,Se,me,Se)}r.stroke()}r.strokeStyle="lightgray";for(const[M,q]of D.entries()){const[H,P]=d(q.x1,q.y1),[$,ee]=d(q.x2,q.y2);r.fillStyle=f(x.get(M)),r.beginPath(),r.rect(H,P,$-H,ee-P),r.fill(),r.stroke()}if(i.value){const M=_(),[q,H]=d(M.x1,M.y1),[P,$]=d(M.x2,M.y2);r.fillStyle="rgba(255, 255, 255, 0.2)",r.fillRect(q,H,P-q,$-H)}},d=(C,A)=>[(C-a.x1)/(a.x2-a.x1)*r.canvas.width,(A-a.y1)/(a.y2-a.y1)*r.canvas.height],h=(C,A)=>[C*(a.x2-a.x1)/r.canvas.width+a.x1,A*(a.y2-a.y1)/r.canvas.height+a.y1],f=C=>{if(C){const A=C.querySelector(".__content");if(A){const x=m(A);if(x)return x}const D=m(C);if(D)return D}return"gray"},m=C=>{const A=getComputedStyle(C).backgroundColor;if(A&&A!=="rgba(0, 0, 0, 0)")return A},_=()=>{const C=s.value.parentElement.offsetWidth,A=s.value.parentElement.offsetHeight,D=C/n.value.scaling-n.value.panning.x,x=A/n.value.scaling-n.value.panning.y;return{x1:-n.value.panning.x,y1:-n.value.panning.y,x2:D,y2:x}},E=C=>{C.button===0&&(o=!0,b(C))},b=C=>{if(o){const[A,D]=h(C.offsetX,C.offsetY),x=_(),O=(x.x2-x.x1)/2,B=(x.y2-x.y1)/2;n.value.panning.x=-(A-O),n.value.panning.y=-(D-B)}},g=()=>{o=!1},y=()=>{i.value=!0},v=()=>{i.value=!1,g()};Mn([i,n.value.panning,()=>n.value.scaling,()=>n.value.connections.length],()=>{u()});const S=et(()=>n.value.nodes.map(C=>C.position)),R=et(()=>n.value.nodes.map(C=>C.width));return Mn([S,R],()=>{u()},{deep:!0}),si(()=>{r=s.value.getContext("2d"),r.imageSmoothingQuality="high",u(),c=setInterval(u,500)}),Ca(()=>{clearInterval(c)}),(C,A)=>(T(),w("canvas",{ref_key:"canvas",ref:s,class:"baklava-minimap",onMouseenter:y,onMouseleave:v,onMousedown:ae(E,["self"]),onMousemove:ae(b,["self"]),onMouseup:g},null,544))}}),rLt=cn({components:{ContextMenu:zE,VerticalDots:rI},props:{type:{type:String,required:!0},title:{type:String,required:!0}},setup(t){const{viewModel:e}=vs(),{switchGraph:n}=Bs(),s=lt(!1),i=et(()=>t.type.startsWith(Gl));return{showContextMenu:s,hasContextMenu:i,contextMenuItems:[{label:"Edit Subgraph",value:"editSubgraph"},{label:"Delete Subgraph",value:"deleteSubgraph"}],openContextMenu:()=>{s.value=!0},onContextMenuClick:c=>{const u=t.type.substring(Gl.length),d=e.value.editor.graphTemplates.find(h=>h.id===u);if(d)switch(c){case"editSubgraph":n(d);break;case"deleteSubgraph":e.value.editor.removeGraphTemplate(d);break}}}}}),oLt=["data-node-type"],aLt={class:"__title"},lLt={class:"__title-label"},cLt={key:0,class:"__menu"};function dLt(t,e,n,s,i,r){const o=at("vertical-dots"),a=at("context-menu");return T(),w("div",{class:"baklava-node --palette","data-node-type":t.type},[l("div",aLt,[l("div",lLt,X(t.title),1),t.hasContextMenu?(T(),w("div",cLt,[he(o,{class:"--clickable",onPointerdown:e[0]||(e[0]=ae(()=>{},["stop","prevent"])),onClick:ae(t.openContextMenu,["stop","prevent"])},null,8,["onClick"]),he(a,{modelValue:t.showContextMenu,"onUpdate:modelValue":e[1]||(e[1]=c=>t.showContextMenu=c),x:-100,y:0,items:t.contextMenuItems,onClick:t.onContextMenuClick,onPointerdown:e[2]||(e[2]=ae(()=>{},["stop","prevent"]))},null,8,["modelValue","items","onClick"])])):G("",!0)])],8,oLt)}const tw=dn(rLt,[["render",dLt]]),uLt={class:"baklava-node-palette"},pLt={key:0},_Lt=cn({__name:"NodePalette",setup(t){const{viewModel:e}=vs(),{x:n,y:s}=ykt(),{transform:i}=eI(),r=JO(e),o=Zn("editorEl"),a=lt(null),c=et(()=>{if(!a.value||!(o!=null&&o.value))return{};const{left:d,top:h}=o.value.getBoundingClientRect();return{top:`${s.value-h}px`,left:`${n.value-d}px`}}),u=(d,h)=>{a.value={type:d,nodeInformation:h};const f=()=>{const m=Wn(new h.type);e.value.displayedGraph.addNode(m);const _=o.value.getBoundingClientRect(),[E,b]=i(n.value-_.left,s.value-_.top);m.position.x=E,m.position.y=b,a.value=null,document.removeEventListener("pointerup",f)};document.addEventListener("pointerup",f)};return(d,h)=>(T(),w(Ve,null,[l("div",uLt,[(T(!0),w(Ve,null,Ze(Ct(r),f=>(T(),w("section",{key:f.name},[f.name!=="default"?(T(),w("h1",pLt,X(f.name),1)):G("",!0),(T(!0),w(Ve,null,Ze(f.nodeTypes,(m,_)=>(T(),wt(tw,{key:_,type:_,title:m.title,onPointerdown:E=>u(_,m)},null,8,["type","title","onPointerdown"]))),128))]))),128))]),he(Ds,{name:"fade"},{default:We(()=>[a.value?(T(),w("div",{key:0,class:"baklava-dragged-node",style:$t(c.value)},[he(tw,{type:a.value.type,title:a.value.nodeInformation.title},null,8,["type","title"])],4)):G("",!0)]),_:1})],64))}});let id;const hLt=new Uint8Array(16);function fLt(){if(!id&&(id=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!id))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return id(hLt)}const vn=[];for(let t=0;t<256;++t)vn.push((t+256).toString(16).slice(1));function mLt(t,e=0){return vn[t[e+0]]+vn[t[e+1]]+vn[t[e+2]]+vn[t[e+3]]+"-"+vn[t[e+4]]+vn[t[e+5]]+"-"+vn[t[e+6]]+vn[t[e+7]]+"-"+vn[t[e+8]]+vn[t[e+9]]+"-"+vn[t[e+10]]+vn[t[e+11]]+vn[t[e+12]]+vn[t[e+13]]+vn[t[e+14]]+vn[t[e+15]]}const gLt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),nw={randomUUID:gLt};function Jd(t,e,n){if(nw.randomUUID&&!e&&!t)return nw.randomUUID();t=t||{};const s=t.random||(t.rng||fLt)();if(s[6]=s[6]&15|64,s[8]=s[8]&63|128,e){n=n||0;for(let i=0;i<16;++i)e[n+i]=s[i];return e}return mLt(s)}const Vl="SAVE_SUBGRAPH";function bLt(t,e){const n=()=>{const s=t.value;if(!s.template)throw new Error("Graph template property not set");s.template.update(s.save()),s.template.panning=s.panning,s.template.scaling=s.scaling};e.registerCommand(Vl,{canExecute:()=>{var s;return t.value!==((s=t.value.editor)==null?void 0:s.graph)},execute:n})}const ELt={},yLt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},vLt=l("polyline",{points:"6 9 12 15 18 9"},null,-1),SLt=[vLt];function TLt(t,e){return T(),w("svg",yLt,SLt)}const xLt=dn(ELt,[["render",TLt]]),CLt=cn({components:{"i-arrow":xLt},props:{intf:{type:Object,required:!0}},setup(t){const e=lt(null),n=lt(!1),s=et(()=>t.intf.items.find(o=>typeof o=="string"?o===t.intf.value:o.value===t.intf.value)),i=et(()=>s.value?typeof s.value=="string"?s.value:s.value.text:""),r=o=>{t.intf.value=typeof o=="string"?o:o.value};return sI(e,()=>{n.value=!1}),{el:e,open:n,selectedItem:s,selectedText:i,setSelected:r}}}),wLt=["title"],RLt={class:"__selected"},ALt={class:"__text"},NLt={class:"__icon"},OLt={class:"__dropdown"},ILt={class:"item --header"},MLt=["onClick"];function DLt(t,e,n,s,i,r){const o=at("i-arrow");return T(),w("div",{ref:"el",class:Fe(["baklava-select",{"--open":t.open}]),title:t.intf.name,onClick:e[0]||(e[0]=a=>t.open=!t.open)},[l("div",RLt,[l("div",ALt,X(t.selectedText),1),l("div",NLt,[he(o)])]),he(Ds,{name:"slide-fade"},{default:We(()=>[U(l("div",OLt,[l("div",ILt,X(t.intf.name),1),(T(!0),w(Ve,null,Ze(t.intf.items,(a,c)=>(T(),w("div",{key:c,class:Fe(["item",{"--active":a===t.selectedItem}]),onClick:u=>t.setSelected(a)},X(typeof a=="string"?a:a.text),11,MLt))),128))],512),[[xt,t.open]])]),_:1})],10,wLt)}const kLt=dn(CLt,[["render",DLt]]);class LLt extends Xt{constructor(e,n,s){super(e,n),this.component=zl(kLt),this.items=s}}const PLt=cn({props:{intf:{type:Object,required:!0}}});function ULt(t,e,n,s,i,r){return T(),w("div",null,X(t.intf.value),1)}const FLt=dn(PLt,[["render",ULt]]);class BLt extends Xt{constructor(e,n){super(e,n),this.component=zl(FLt),this.setPort(!1)}}const GLt=cn({props:{intf:{type:Object,required:!0},modelValue:{type:String,required:!0}},emits:["update:modelValue"],setup(t,{emit:e}){return{v:et({get:()=>t.modelValue,set:s=>{e("update:modelValue",s)}})}}}),VLt=["placeholder","title"];function zLt(t,e,n,s,i,r){return T(),w("div",null,[U(l("input",{"onUpdate:modelValue":e[0]||(e[0]=o=>t.v=o),type:"text",class:"baklava-input",placeholder:t.intf.name,title:t.intf.name},null,8,VLt),[[ue,t.v]])])}const HLt=dn(GLt,[["render",zLt]]);class tc extends Xt{constructor(){super(...arguments),this.component=zl(HLt)}}class aI extends WO{constructor(){super(...arguments),this._title="Subgraph Input",this.inputs={name:new tc("Name","Input").setPort(!1)},this.outputs={placeholder:new Xt("Connection",void 0)}}}class lI extends KO{constructor(){super(...arguments),this._title="Subgraph Output",this.inputs={name:new tc("Name","Output").setPort(!1),placeholder:new Xt("Connection",void 0)},this.outputs={output:new Xt("Output",void 0).setHidden(!0)}}}const cI="CREATE_SUBGRAPH",sw=[ga,ba];function qLt(t,e,n){const s=()=>t.value.selectedNodes.filter(r=>!sw.includes(r.type)).length>0,i=()=>{const{viewModel:r}=vs(),o=t.value,a=t.value.editor;if(o.selectedNodes.length===0)return;const c=o.selectedNodes.filter(x=>!sw.includes(x.type)),u=c.flatMap(x=>Object.values(x.inputs)),d=c.flatMap(x=>Object.values(x.outputs)),h=o.connections.filter(x=>!d.includes(x.from)&&u.includes(x.to)),f=o.connections.filter(x=>d.includes(x.from)&&!u.includes(x.to)),m=o.connections.filter(x=>d.includes(x.from)&&u.includes(x.to)),_=c.map(x=>x.save()),E=m.map(x=>({id:x.id,from:x.from.id,to:x.to.id})),b=new Map,{xLeft:g,xRight:y,yTop:v}=YLt(c);console.log(g,y,v);for(const[x,O]of h.entries()){const B=new aI;B.inputs.name.value=O.to.name,_.push({...B.save(),position:{x:y-r.value.settings.nodes.defaultWidth-100,y:v+x*200}}),E.push({id:Jd(),from:B.outputs.placeholder.id,to:O.to.id}),b.set(O.to.id,B.graphInterfaceId)}for(const[x,O]of f.entries()){const B=new lI;B.inputs.name.value=O.from.name,_.push({...B.save(),position:{x:g+100,y:v+x*200}}),E.push({id:Jd(),from:O.from.id,to:B.inputs.placeholder.id}),b.set(O.from.id,B.graphInterfaceId)}const S=Wn(new Wu({connections:E,nodes:_,inputs:[],outputs:[]},a));a.addGraphTemplate(S);const R=a.nodeTypes.get(Ea(S));if(!R)throw new Error("Unable to create subgraph: Could not find corresponding graph node type");const C=Wn(new R.type);o.addNode(C);const A=Math.round(c.map(x=>x.position.x).reduce((x,O)=>x+O,0)/c.length),D=Math.round(c.map(x=>x.position.y).reduce((x,O)=>x+O,0)/c.length);C.position.x=A,C.position.y=D,h.forEach(x=>{o.removeConnection(x),o.addConnection(x.from,C.inputs[b.get(x.to.id)])}),f.forEach(x=>{o.removeConnection(x),o.addConnection(C.outputs[b.get(x.from.id)],x.to)}),c.forEach(x=>o.removeNode(x)),e.canExecuteCommand(Vl)&&e.executeCommand(Vl),n(S),t.value.panning={...o.panning},t.value.scaling=o.scaling};e.registerCommand(cI,{canExecute:s,execute:i})}function YLt(t){const e=t.reduce((i,r)=>{const o=r.position.x;return o{const o=r.position.y;return o{const o=r.position.x+r.width;return o>i?o:i},-1/0),xRight:e,yTop:n}}const iw="DELETE_NODES";function $Lt(t,e){e.registerCommand(iw,{canExecute:()=>t.value.selectedNodes.length>0,execute(){t.value.selectedNodes.forEach(n=>t.value.removeNode(n))}}),e.registerHotkey(["Delete"],iw)}const dI="SWITCH_TO_MAIN_GRAPH";function WLt(t,e,n){e.registerCommand(dI,{canExecute:()=>t.value!==t.value.editor.graph,execute:()=>{e.executeCommand(Vl),n(t.value.editor.graph)}})}function KLt(t,e,n){$Lt(t,e),qLt(t,e,n),bLt(t,e),WLt(t,e,n)}class rw{constructor(e,n){this.type=e,e==="addNode"?this.nodeId=n:this.nodeState=n}undo(e){this.type==="addNode"?this.removeNode(e):this.addNode(e)}redo(e){this.type==="addNode"&&this.nodeState?this.addNode(e):this.type==="removeNode"&&this.nodeId&&this.removeNode(e)}addNode(e){const n=e.editor.nodeTypes.get(this.nodeState.type);if(!n)return;const s=new n.type;e.addNode(s),s.load(this.nodeState),this.nodeId=s.id}removeNode(e){const n=e.nodes.find(s=>s.id===this.nodeId);n&&(this.nodeState=n.save(),e.removeNode(n))}}class ow{constructor(e,n){if(this.type=e,e==="addConnection")this.connectionId=n;else{const s=n;this.connectionState={id:s.id,from:s.from.id,to:s.to.id}}}undo(e){this.type==="addConnection"?this.removeConnection(e):this.addConnection(e)}redo(e){this.type==="addConnection"&&this.connectionState?this.addConnection(e):this.type==="removeConnection"&&this.connectionId&&this.removeConnection(e)}addConnection(e){const n=e.findNodeInterface(this.connectionState.from),s=e.findNodeInterface(this.connectionState.to);!n||!s||e.addConnection(n,s)}removeConnection(e){const n=e.connections.find(s=>s.id===this.connectionId);n&&(this.connectionState={id:n.id,from:n.from.id,to:n.to.id},e.removeConnection(n))}}class jLt{constructor(e){if(this.type="transaction",e.length===0)throw new Error("Can't create a transaction with no steps");this.steps=e}undo(e){for(let n=this.steps.length-1;n>=0;n--)this.steps[n].undo(e)}redo(e){for(let n=0;n{if(!r.value)if(a.value)c.value.push(b);else for(o.value!==i.value.length-1&&(i.value=i.value.slice(0,o.value+1)),i.value.push(b),o.value++;i.value.length>s.value;)i.value.shift()},d=()=>{a.value=!0},h=()=>{a.value=!1,c.value.length>0&&(u(new jLt(c.value)),c.value=[])},f=()=>i.value.length!==0&&o.value!==-1,m=()=>{f()&&(r.value=!0,i.value[o.value--].undo(t.value),r.value=!1)},_=()=>i.value.length!==0&&o.value{_()&&(r.value=!0,i.value[++o.value].redo(t.value),r.value=!1)};return Mn(t,(b,g)=>{g&&(g.events.addNode.unsubscribe(n),g.events.removeNode.unsubscribe(n),g.events.addConnection.unsubscribe(n),g.events.removeConnection.unsubscribe(n)),b&&(b.events.addNode.subscribe(n,y=>{u(new rw("addNode",y.id))}),b.events.removeNode.subscribe(n,y=>{u(new rw("removeNode",y.save()))}),b.events.addConnection.subscribe(n,y=>{u(new ow("addConnection",y.id))}),b.events.removeConnection.subscribe(n,y=>{u(new ow("removeConnection",y))}))},{immediate:!0}),e.registerCommand(jg,{canExecute:f,execute:m}),e.registerCommand(Qg,{canExecute:_,execute:E}),e.registerCommand(uI,{canExecute:()=>!a.value,execute:d}),e.registerCommand(pI,{canExecute:()=>a.value,execute:h}),e.registerHotkey(["Control","z"],jg),e.registerHotkey(["Control","y"],Qg),Wn({maxSteps:s})}const Xg="COPY",Zg="PASTE",XLt="CLEAR_CLIPBOARD";function ZLt(t,e,n){const s=Symbol("ClipboardToken"),i=lt(""),r=lt(""),o=et(()=>!i.value),a=()=>{i.value="",r.value=""},c=()=>{const h=t.value.selectedNodes.flatMap(m=>[...Object.values(m.inputs),...Object.values(m.outputs)]),f=t.value.connections.filter(m=>h.includes(m.from)||h.includes(m.to)).map(m=>({from:m.from.id,to:m.to.id}));r.value=JSON.stringify(f),i.value=JSON.stringify(t.value.selectedNodes.map(m=>m.save()))},u=(h,f,m)=>{for(const _ of h){let E;if((!m||m==="input")&&(E=Object.values(_.inputs).find(b=>b.id===f)),!E&&(!m||m==="output")&&(E=Object.values(_.outputs).find(b=>b.id===f)),E)return E}},d=()=>{if(o.value)return;const h=new Map,f=JSON.parse(i.value),m=JSON.parse(r.value),_=[],E=[],b=t.value;n.executeCommand(uI);for(const g of f){const y=e.value.nodeTypes.get(g.type);if(!y){console.warn(`Node type ${g.type} not registered`);return}const v=new y.type,S=v.id;_.push(v),v.hooks.beforeLoad.subscribe(s,R=>{const C=R;return C.position&&(C.position.x+=100,C.position.y+=100),v.hooks.beforeLoad.unsubscribe(s),C}),b.addNode(v),v.load({...g,id:S}),v.id=S,h.set(g.id,S);for(const R of Object.values(v.inputs)){const C=Jd();h.set(R.id,C),R.id=C}for(const R of Object.values(v.outputs)){const C=Jd();h.set(R.id,C),R.id=C}}for(const g of m){const y=u(_,h.get(g.from),"output"),v=u(_,h.get(g.to),"input");if(!y||!v)continue;const S=b.addConnection(y,v);S&&E.push(S)}return t.value.selectedNodes=_,n.executeCommand(pI),{newNodes:_,newConnections:E}};return n.registerCommand(Xg,{canExecute:()=>t.value.selectedNodes.length>0,execute:c}),n.registerHotkey(["Control","c"],Xg),n.registerCommand(Zg,{canExecute:()=>!o.value,execute:d}),n.registerHotkey(["Control","v"],Zg),n.registerCommand(XLt,{canExecute:()=>!0,execute:a}),Wn({isEmpty:o})}const JLt="OPEN_SIDEBAR";function ePt(t,e){e.registerCommand(JLt,{execute:n=>{t.value.sidebar.nodeId=n,t.value.sidebar.visible=!0},canExecute:()=>!0})}function tPt(t,e){ePt(t,e)}const nPt={},sPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},iPt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),rPt=l("path",{d:"M9 13l-4 -4l4 -4m-4 4h11a4 4 0 0 1 0 8h-1"},null,-1),oPt=[iPt,rPt];function aPt(t,e){return T(),w("svg",sPt,oPt)}const lPt=dn(nPt,[["render",aPt]]),cPt={},dPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},uPt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),pPt=l("path",{d:"M15 13l4 -4l-4 -4m4 4h-11a4 4 0 0 0 0 8h1"},null,-1),_Pt=[uPt,pPt];function hPt(t,e){return T(),w("svg",dPt,_Pt)}const fPt=dn(cPt,[["render",hPt]]),mPt={},gPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},bPt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),EPt=l("line",{x1:"5",y1:"12",x2:"19",y2:"12"},null,-1),yPt=l("line",{x1:"5",y1:"12",x2:"11",y2:"18"},null,-1),vPt=l("line",{x1:"5",y1:"12",x2:"11",y2:"6"},null,-1),SPt=[bPt,EPt,yPt,vPt];function TPt(t,e){return T(),w("svg",gPt,SPt)}const xPt=dn(mPt,[["render",TPt]]),CPt={},wPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},RPt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),APt=l("path",{d:"M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2"},null,-1),NPt=l("rect",{x:"9",y:"3",width:"6",height:"4",rx:"2"},null,-1),OPt=[RPt,APt,NPt];function IPt(t,e){return T(),w("svg",wPt,OPt)}const MPt=dn(CPt,[["render",IPt]]),DPt={},kPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},LPt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),PPt=l("rect",{x:"8",y:"8",width:"12",height:"12",rx:"2"},null,-1),UPt=l("path",{d:"M16 8v-2a2 2 0 0 0 -2 -2h-8a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h2"},null,-1),FPt=[LPt,PPt,UPt];function BPt(t,e){return T(),w("svg",kPt,FPt)}const GPt=dn(DPt,[["render",BPt]]),VPt={},zPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},HPt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),qPt=l("path",{d:"M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2"},null,-1),YPt=l("circle",{cx:"12",cy:"14",r:"2"},null,-1),$Pt=l("polyline",{points:"14 4 14 8 8 8 8 4"},null,-1),WPt=[HPt,qPt,YPt,$Pt];function KPt(t,e){return T(),w("svg",zPt,WPt)}const jPt=dn(VPt,[["render",KPt]]),QPt={},XPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},ZPt=fu('',6),JPt=[ZPt];function eUt(t,e){return T(),w("svg",XPt,JPt)}const tUt=dn(QPt,[["render",eUt]]),nUt=cn({props:{command:{type:String,required:!0},title:{type:String,required:!0},icon:{type:Object,required:!1,default:void 0}},setup(){const{viewModel:t}=vs();return{viewModel:t}}}),sUt=["disabled","title"];function iUt(t,e,n,s,i,r){return T(),w("button",{class:"baklava-toolbar-entry baklava-toolbar-button",disabled:!t.viewModel.commandHandler.canExecuteCommand(t.command),title:t.title,onClick:e[0]||(e[0]=o=>t.viewModel.commandHandler.executeCommand(t.command))},[t.icon?(T(),wt(pu(t.icon),{key:0})):(T(),w(Ve,{key:1},[Je(X(t.title),1)],64))],8,sUt)}const rUt=dn(nUt,[["render",iUt]]),oUt=cn({components:{ToolbarButton:rUt},setup(){const{viewModel:t}=vs();return{isSubgraph:et(()=>t.value.displayedGraph!==t.value.editor.graph),commands:[{command:Xg,title:"Copy",icon:GPt},{command:Zg,title:"Paste",icon:MPt},{command:jg,title:"Undo",icon:lPt},{command:Qg,title:"Redo",icon:fPt},{command:cI,title:"Create Subgraph",icon:tUt}],subgraphCommands:[{command:Vl,title:"Save Subgraph",icon:jPt},{command:dI,title:"Back to Main Graph",icon:xPt}]}}}),aUt={class:"baklava-toolbar"};function lUt(t,e,n,s,i,r){const o=at("toolbar-button");return T(),w("div",aUt,[(T(!0),w(Ve,null,Ze(t.commands,a=>(T(),wt(o,{key:a.command,command:a.command,title:a.title,icon:a.icon},null,8,["command","title","icon"]))),128)),t.isSubgraph?(T(!0),w(Ve,{key:0},Ze(t.subgraphCommands,a=>(T(),wt(o,{key:a.command,command:a.command,title:a.title,icon:a.icon},null,8,["command","title","icon"]))),128)):G("",!0)])}const cUt=dn(oUt,[["render",lUt]]),dUt={class:"connections-container"},uUt=cn({__name:"Editor",props:{viewModel:{}},setup(t){const e=t,n=Symbol("EditorToken"),s=xd(e,"viewModel");rkt(s);const i=lt(null);zo("editorEl",i);const r=et(()=>e.viewModel.displayedGraph.nodes),o=et(()=>e.viewModel.displayedGraph.nodes.map(A=>XO(xd(A,"position")))),a=et(()=>e.viewModel.displayedGraph.connections),c=et(()=>e.viewModel.displayedGraph.selectedNodes),u=okt(),d=akt(),h=lkt(s),f=et(()=>({...u.styles.value})),m=lt(0);e.viewModel.editor.hooks.load.subscribe(n,A=>(m.value++,A));const _=A=>{u.onPointerMove(A),d.onMouseMove(A)},E=A=>{A.button===0&&(A.target===i.value&&(S(),u.onPointerDown(A)),d.onMouseDown())},b=A=>{u.onPointerUp(A),d.onMouseUp()},g=A=>{A.key==="Tab"&&A.preventDefault(),e.viewModel.commandHandler.handleKeyDown(A)},y=A=>{e.viewModel.commandHandler.handleKeyUp(A)},v=A=>{["Control","Shift"].some(D=>e.viewModel.commandHandler.pressedKeys.includes(D))||S(),e.viewModel.displayedGraph.selectedNodes.push(A)},S=()=>{e.viewModel.displayedGraph.selectedNodes=[]},R=A=>{for(const D of e.viewModel.displayedGraph.selectedNodes){const x=r.value.indexOf(D),O=o.value[x];O.onPointerDown(A),document.addEventListener("pointermove",O.onPointerMove)}document.addEventListener("pointerup",C)},C=()=>{for(const A of e.viewModel.displayedGraph.selectedNodes){const D=r.value.indexOf(A),x=o.value[D];x.onPointerUp(),document.removeEventListener("pointermove",x.onPointerMove)}document.removeEventListener("pointerup",C)};return(A,D)=>(T(),w("div",{ref_key:"el",ref:i,tabindex:"-1",class:Fe(["baklava-editor",{"baklava-ignore-mouse":!!Ct(d).temporaryConnection.value||Ct(u).dragging.value,"--temporary-connection":!!Ct(d).temporaryConnection.value}]),onPointermove:ae(_,["self"]),onPointerdown:E,onPointerup:b,onWheel:D[1]||(D[1]=ae((...x)=>Ct(u).onMouseWheel&&Ct(u).onMouseWheel(...x),["self"])),onKeydown:g,onKeyup:y,onContextmenu:D[2]||(D[2]=ae((...x)=>Ct(h).open&&Ct(h).open(...x),["self","prevent"]))},[An(A.$slots,"background",{},()=>[he(ukt)]),An(A.$slots,"toolbar",{},()=>[he(cUt)]),An(A.$slots,"palette",{},()=>[he(_Lt)]),(T(),w("svg",dUt,[(T(!0),w(Ve,null,Ze(a.value,x=>(T(),w("g",{key:x.id+m.value.toString()},[An(A.$slots,"connection",{connection:x},()=>[he(jkt,{connection:x},null,8,["connection"])])]))),128)),An(A.$slots,"temporaryConnection",{temporaryConnection:Ct(d).temporaryConnection.value},()=>[Ct(d).temporaryConnection.value?(T(),wt(Zkt,{key:0,connection:Ct(d).temporaryConnection.value},null,8,["connection"])):G("",!0)])])),l("div",{class:"node-container",style:$t(f.value)},[he(Xs,{name:"fade"},{default:We(()=>[(T(!0),w(Ve,null,Ze(r.value,(x,O)=>An(A.$slots,"node",{key:x.id+m.value.toString(),node:x,selected:c.value.includes(x),dragging:o.value[O].dragging.value,onSelect:B=>v(x),onStartDrag:R},()=>[he(zkt,{node:x,selected:c.value.includes(x),dragging:o.value[O].dragging.value,onSelect:B=>v(x),onStartDrag:R},null,8,["node","selected","dragging","onSelect"])])),128))]),_:3})],4),An(A.$slots,"sidebar",{},()=>[he(sLt)]),An(A.$slots,"minimap",{},()=>[A.viewModel.settings.enableMinimap?(T(),wt(iLt,{key:0})):G("",!0)]),An(A.$slots,"contextMenu",{contextMenu:Ct(h)},()=>[A.viewModel.settings.contextMenu.enabled?(T(),wt(zE,{key:0,modelValue:Ct(h).show.value,"onUpdate:modelValue":D[0]||(D[0]=x=>Ct(h).show.value=x),items:Ct(h).items.value,x:Ct(h).x.value,y:Ct(h).y.value,onClick:Ct(h).onClick},null,8,["modelValue","items","x","y","onClick"])):G("",!0)])],34))}}),pUt=["INPUT","TEXTAREA","SELECT"];function _Ut(t){const e=lt([]),n=lt([]);return{pressedKeys:e,handleKeyDown:o=>{var a;e.value.includes(o.key)||e.value.push(o.key),!pUt.includes(((a=document.activeElement)==null?void 0:a.tagName)??"")&&n.value.forEach(c=>{c.keys.every(u=>e.value.includes(u))&&t(c.commandName)})},handleKeyUp:o=>{const a=e.value.indexOf(o.key);a>=0&&e.value.splice(a,1)},registerHotkey:(o,a)=>{n.value.push({keys:o,commandName:a})}}}const hUt=()=>{const t=lt(new Map),e=(r,o)=>{if(t.value.has(r))throw new Error(`Command "${r}" already exists`);t.value.set(r,o)},n=(r,o=!1,...a)=>{if(!t.value.has(r)){if(o)throw new Error(`[CommandHandler] Command ${r} not registered`);return}return t.value.get(r).execute(...a)},s=(r,o=!1,...a)=>{if(!t.value.has(r)){if(o)throw new Error(`[CommandHandler] Command ${r} not registered`);return!1}return t.value.get(r).canExecute(a)},i=_Ut(n);return Wn({registerCommand:e,executeCommand:n,canExecuteCommand:s,...i})},fUt=t=>!(t instanceof ec);function mUt(t,e){return{switchGraph:s=>{let i;if(fUt(s))i=new ec(t.value),s.createGraph(i);else{if(s!==t.value.graph)throw new Error("Can only switch using 'Graph' instance when it is the root graph. Otherwise a 'GraphTemplate' must be used.");i=s}e.value&&e.value!==t.value.graph&&e.value.destroy(),i.panning=i.panning??s.panning??{x:0,y:0},i.scaling=i.scaling??s.scaling??1,i.selectedNodes=i.selectedNodes??[],i.sidebar=i.sidebar??{visible:!1,nodeId:"",optionName:""},e.value=i}}}function gUt(t,e){t.position=t.position??{x:0,y:0},t.disablePointerEvents=!1,t.twoColumn=t.twoColumn??!1,t.width=t.width??e.defaultWidth}const bUt=()=>({useStraightConnections:!1,enableMinimap:!1,background:{gridSize:100,gridDivision:5,subGridVisibleThreshold:.6},sidebar:{width:300,resizable:!0},displayValueOnHover:!1,nodes:{defaultWidth:200,maxWidth:320,minWidth:150,resizable:!1},contextMenu:{enabled:!0,additionalItems:[]}});function EUt(t){const e=lt(t??new JDt),n=Symbol("ViewModelToken"),s=lt(null),i=mM(s),{switchGraph:r}=mUt(e,s),o=et(()=>i.value&&i.value!==e.value.graph),a=Wn(bUt()),c=hUt(),u=QLt(i,c),d=ZLt(i,e,c),h={renderNode:new ts(null),renderInterface:new ts(null)};return KLt(i,c,r),tPt(i,c),Mn(e,(f,m)=>{m&&(m.events.registerGraph.unsubscribe(n),m.graphEvents.beforeAddNode.unsubscribe(n),f.nodeHooks.beforeLoad.unsubscribe(n),f.nodeHooks.afterSave.unsubscribe(n),f.graphTemplateHooks.beforeLoad.unsubscribe(n),f.graphTemplateHooks.afterSave.unsubscribe(n),f.graph.hooks.load.unsubscribe(n),f.graph.hooks.save.unsubscribe(n)),f&&(f.nodeHooks.beforeLoad.subscribe(n,(_,E)=>(E.position=_.position??{x:0,y:0},E.width=_.width??a.nodes.defaultWidth,E.twoColumn=_.twoColumn??!1,_)),f.nodeHooks.afterSave.subscribe(n,(_,E)=>(_.position=E.position,_.width=E.width,_.twoColumn=E.twoColumn,_)),f.graphTemplateHooks.beforeLoad.subscribe(n,(_,E)=>(E.panning=_.panning,E.scaling=_.scaling,_)),f.graphTemplateHooks.afterSave.subscribe(n,(_,E)=>(_.panning=E.panning,_.scaling=E.scaling,_)),f.graph.hooks.load.subscribe(n,(_,E)=>(E.panning=_.panning,E.scaling=_.scaling,_)),f.graph.hooks.save.subscribe(n,(_,E)=>(_.panning=E.panning,_.scaling=E.scaling,_)),f.graphEvents.beforeAddNode.subscribe(n,_=>gUt(_,{defaultWidth:a.nodes.defaultWidth})),e.value.registerNodeType(aI,{category:"Subgraphs"}),e.value.registerNodeType(lI,{category:"Subgraphs"}),r(f.graph))},{immediate:!0}),Wn({editor:e,displayedGraph:i,isSubgraph:o,settings:a,commandHandler:c,history:u,clipboard:d,hooks:h,switchGraph:r})}const yUt=Ua({type:"PersonalityNode",title:"Personality",inputs:{request:()=>new Xt("Request",""),agent_name:()=>new LLt("Personality","",Rs.state.config.personalities).setPort(!1)},outputs:{response:()=>new Xt("Response","")},async calculate({request:t}){console.log(Rs.state.config.personalities);let e="";try{e=(await de.post("/generate",{params:{text:t}})).data}catch(n){console.error(n)}return{display:e,response:e}}}),vUt=Ua({type:"RAGNode",title:"RAG",inputs:{request:()=>new Xt("Prompt",""),document_path:()=>new tc("Document path","").setPort(!1)},outputs:{prompt:()=>new Xt("Prompt with Data","")},async calculate({request:t,document_path:e}){let n="";try{n=(await de.get("/rag",{params:{text:t,doc_path:e}})).data}catch(s){console.error(s)}return{response:n}}}),aw=Ua({type:"Task",title:"Task",inputs:{description:()=>new tc("Task description","").setPort(!1)},outputs:{prompt:()=>new Xt("Prompt")},calculate({description:t}){return{prompt:t}}}),lw=Ua({type:"TextDisplayNode",title:"TextDisplay",inputs:{text2display:()=>new Xt("Input","")},outputs:{response:()=>new BLt("Text","")},async calculate({request:t}){}}),cw=Ua({type:"LLMNode",title:"LLM",inputs:{request:()=>new Xt("Request","")},outputs:{response:()=>new Xt("Response","")},async calculate({request:t}){console.log(Rs.state.config.personalities);let e="";try{e=(await de.post("/generate",{params:{text:t}})).data}catch(n){console.error(n)}return{display:e,response:e}}}),SUt=Ua({type:"MultichoiceNode",title:"Multichoice",inputs:{question:()=>new Xt("Question",""),outputs:()=>new tc("choices, one per line","","").setPort(!1)},outputs:{response:()=>new Xt("Response","")}}),TUt=cn({components:{"baklava-editor":uUt},setup(){const t=EUt(),e=new ikt(t.editor);t.editor.registerNodeType(yUt),t.editor.registerNodeType(aw),t.editor.registerNodeType(vUt),t.editor.registerNodeType(lw),t.editor.registerNodeType(cw),t.editor.registerNodeType(SUt);const n=Symbol();e.events.afterRun.subscribe(n,a=>{e.pause(),ekt(a,t.editor),e.resume()}),e.start();function s(a,c,u){const d=new a;return t.displayedGraph.addNode(d),d.position.x=c,d.position.y=u,d}const i=s(aw,300,140),r=s(cw,550,140),o=s(lw,850,140);return t.displayedGraph.addConnection(i.outputs.prompt,r.inputs.request),t.displayedGraph.addConnection(r.outputs.response,o.inputs.text2display),{baklava:t,saveGraph:()=>{const a=e.export();localStorage.setItem("myGraph",JSON.stringify(a))},loadGraph:()=>{const a=JSON.parse(localStorage.getItem("myGraph"));e.import(a)}}}}),xUt={style:{width:"100vw",height:"100vh"}};function CUt(t,e,n,s,i,r){const o=at("baklava-editor");return T(),w("div",xUt,[he(o,{"view-model":t.baklava},null,8,["view-model"]),l("button",{onClick:e[0]||(e[0]=(...a)=>t.saveGraph&&t.saveGraph(...a))},"Save Graph"),l("button",{onClick:e[1]||(e[1]=(...a)=>t.loadGraph&&t.loadGraph(...a))},"Load Graph")])}const wUt=ct(TUt,[["render",CUt]]),RUt={},AUt={style:{width:"100vw",height:"100vh"}},NUt=["src"];function OUt(t,e,n,s,i,r){return T(),w("div",AUt,[l("iframe",{src:t.$store.state.config.comfyui_base_url,class:"m-0 p-0 w-full h-full"},null,8,NUt)])}const IUt=ct(RUt,[["render",OUt]]),MUt={},DUt={style:{width:"100vw",height:"100vh"}},kUt=["src"];function LUt(t,e,n,s,i,r){return T(),w("div",DUt,[l("iframe",{src:t.$store.state.config.sd_base_url,class:"m-0 p-0 w-full h-full"},null,8,kUt)])}const PUt=ct(MUt,[["render",LUt]]),UUt={data(){return{apps:[],githubApps:[],selectedApp:null,appCode:"",loading:!1,message:"",successMessage:!0,searchQuery:"",selectedFile:null,isUploading:!1,message:"",error:""}},computed:{combinedApps(){this.apps.map(e=>e.name);const t=new Map(this.apps.map(e=>[e.name,{...e,installed:!0,existsInFolder:!0}]));return this.githubApps.forEach(e=>{t.has(e.name)||t.set(e.name,{...e,installed:!1,existsInFolder:!1})}),Array.from(t.values())},filteredApps(){return this.combinedApps.filter(t=>t.name.toLowerCase().includes(this.searchQuery.toLowerCase())||t.description.toLowerCase().includes(this.searchQuery.toLowerCase()))},categories(){return[...new Set(this.combinedApps.map(t=>t.category))]}},methods:{startServer(t){const e={client_id:this.$store.state.client_id,app_name:t};de.post("/apps/start_server",e).then(n=>{console.log("Server start initiated:",n.data.message),this.$notify({type:"success",title:"Server Starting",text:n.data.message})}).catch(n=>{var s,i;console.error("Error starting server:",n),this.$notify({type:"error",title:"Server Start Failed",text:((i=(s=n.response)==null?void 0:s.data)==null?void 0:i.detail)||"An error occurred while starting the server"})})},triggerFileInput(){this.$refs.fileInput.click()},onFileSelected(t){this.selectedFile=t.target.files[0],this.message="",this.error="",this.uploadApp()},async uploadApp(){var e,n;if(!this.selectedFile){this.error="Please select a file to upload.";return}this.isUploading=!0,this.message="",this.error="";const t=new FormData;t.append("file",this.selectedFile),t.append("client_id",this.$store.state.client_id);try{const s=await de.post("/upload_app",t,{headers:{"Content-Type":"multipart/form-data"}});this.message=s.data.message,this.$refs.fileInput.value="",this.selectedFile=null}catch(s){console.error("Error uploading app:",s),this.error=((n=(e=s.response)==null?void 0:e.data)==null?void 0:n.detail)||"Failed to upload the app. Please try again."}finally{this.isUploading=!1}},async fetchApps(){this.loading=!0;try{const t=await de.get("/apps");this.apps=t.data,this.showMessage("Refresh successful!",!0)}catch{this.showMessage("Failed to refresh apps.",!1)}finally{this.loading=!1}},async openAppsFolder(){this.loading=!0;try{console.log("opening apps folder");const t=await de.post("/show_apps_folder",{client_id:this.$store.state.client_id})}catch{this.showMessage("Failed to open apps folder.",!1)}finally{this.loading=!1}},async fetchGithubApps(){this.loading=!0;try{const t=await de.get("/github/apps");this.githubApps=t.data.apps,await this.fetchApps()}catch{this.showMessage("Failed to refresh GitHub apps.",!1)}finally{this.loading=!1}},async handleAppClick(t){if(t.installed){this.selectedApp=t;const e=await de.get(`/apps/${t.folder_name}/index.html`);this.appCode=e.data}else this.showMessage(`Please install ${t.folder_name} to view its code.`,!1)},backToZoo(){this.selectedApp=null,this.appCode=""},async installApp(t){this.loading=!0;try{await de.post(`/install/${t}`,{client_id:this.$store.state.client_id}),this.showMessage("Installation succeeded!",!0)}catch{this.showMessage("Installation failed.",!1)}finally{this.loading=!1,this.fetchApps(),this.fetchGithubApps()}},async uninstallApp(t){this.loading=!0;try{await de.post(`/uninstall/${t}`,{client_id:this.$store.state.client_id}),this.showMessage("Uninstallation succeeded!",!0)}catch{this.showMessage("Uninstallation failed.",!1)}finally{this.loading=!1,this.fetchApps()}},async deleteApp(t){this.loading=!0;try{await de.post(`/delete/${t}`,{client_id:this.$store.state.client_id}),this.showMessage("Deletion succeeded!",!0)}catch{this.showMessage("Deletion failed.",!1)}finally{this.loading=!1,this.fetchApps()}},async editApp(t){this.loading=!0;try{const e=await de.post("/open_app_in_vscode",{client_id:this.$store.state.client_id,app_name:t.folder_name});this.showMessage(e.data.message,!0)}catch{this.showMessage("Failed to open folder in VSCode.",!1)}finally{this.loading=!1}},async downloadApp(t){this.isLoading=!0,this.error=null;try{const e=await de.post("/download_app",{client_id:this.$store.state.client_id,app_name:t}),n=e.headers["content-disposition"],s=n&&n.match(/filename="?(.+)"?/i),i=s?s[1]:"app.zip",r=new Blob([e.data],{type:"application/zip"}),o=window.URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=o,a.download=i,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o),document.body.removeChild(a)}catch(e){console.error("Error downloading app:",e),this.error="Failed to download the app. Please try again."}finally{this.isLoading=!1}},openApp(t){t.installed?window.open(`/apps/${t.folder_name}/index.html?client_id=${this.$store.state.client_id}`,"_blank"):this.showMessage(`Please install ${t.name} before opening.`,!1)},showMessage(t,e){this.message=t,this.successMessage=e,setTimeout(()=>{this.message=""},3e3)}},mounted(){this.fetchGithubApps()}},FUt={class:"app-zoo background-color w-full p-6 overflow-y-auto scrollbar-thin scrollbar-track-bg-light-tone scrollbar-thumb-bg-light-tone-panel hover:scrollbar-thumb-primary dark:scrollbar-track-bg-dark-tone dark:scrollbar-thumb-bg-dark-tone-panel dark:hover:scrollbar-thumb-primary active:scrollbar-thumb-secondary"},BUt={class:"panels-color shadow-lg rounded-lg p-4 max-w-4xl mx-auto"},GUt={class:"flex flex-wrap items-center justify-between gap-4"},VUt={class:"flex items-center space-x-4"},zUt=l("svg",{class:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})],-1),HUt=l("svg",{class:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M5 19a2 2 0 01-2-2V7a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1M5 19h14a2 2 0 002-2v-5a2 2 0 00-2-2H9a2 2 0 00-2 2v5a2 2 0 01-2 2z"})],-1),qUt=["disabled"],YUt={key:0},$Ut={key:1,class:"error"},WUt={class:"relative flex-grow max-w-md"},KUt=l("svg",{class:"w-5 h-5 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})],-1),jUt={key:0,class:"flex justify-center items-center space-x-2 my-8","aria-live":"polite"},QUt=l("div",{class:"animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-blue-500"},null,-1),XUt=l("span",{class:"text-xl text-gray-700 font-semibold"},"Loading...",-1),ZUt=[QUt,XUt],JUt={class:"text-3xl font-bold mb-6 text-gray-800"},eFt={class:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8"},tFt={class:"flex-grow"},nFt={class:"flex items-center mb-4"},sFt=["src"],iFt={class:"font-bold text-xl text-gray-800"},rFt={class:"text-sm text-gray-600"},oFt={class:"text-sm text-gray-600"},aFt={class:"mb-4"},lFt=l("h4",{class:"font-semibold mb-1 text-gray-700"},"Description:",-1),cFt={class:"text-sm text-gray-600 h-20 overflow-y-auto"},dFt={class:"text-sm text-gray-600 mb-2"},uFt={key:0,class:"mb-4"},pFt=l("h4",{class:"font-semibold mb-1 text-gray-700"},"Disclaimer:",-1),_Ft={class:"text-xs text-gray-500 italic h-16 overflow-y-auto"},hFt={class:"mt-auto pt-4 border-t"},fFt={class:"flex justify-between items-center flex-wrap"},mFt=["onClick"],gFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})],-1),bFt=[gFt],EFt=["onClick"],yFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})],-1),vFt=[yFt],SFt=["onClick"],TFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})],-1),xFt=[TFt],CFt=["onClick"],wFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})],-1),RFt=[wFt],AFt=["onClick"],NFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})],-1),OFt=[NFt],IFt=["onClick"],MFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})],-1),DFt=[MFt],kFt=["onClick"],LFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})],-1),PFt=[LFt],UFt=["onClick"],FFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M5 12h14M12 5l7 7-7 7"})],-1),BFt=[FFt],GFt=["onClick"],VFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})],-1),zFt=l("span",{class:"absolute top-0 right-0 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-red-100 transform translate-x-1/2 -translate-y-1/2 bg-red-600 rounded-full"},"!",-1),HFt=[VFt,zFt],qFt={key:1,class:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"},YFt={class:"bg-white rounded-lg p-6 w-11/12 h-5/6 flex flex-col"},$Ft={class:"flex justify-between items-center mb-4"},WFt={class:"text-2xl font-bold"},KFt=["srcdoc"],jFt={key:1,class:"text-center text-red-500"};function QFt(t,e,n,s,i,r){return T(),w("div",FUt,[l("nav",BUt,[l("div",GUt,[l("div",VUt,[l("button",{onClick:e[0]||(e[0]=(...o)=>r.fetchGithubApps&&r.fetchGithubApps(...o)),class:"btn btn-primary","aria-label":"Refresh apps from GitHub"},[zUt,Je(" Refresh ")]),l("button",{onClick:e[1]||(e[1]=(...o)=>r.openAppsFolder&&r.openAppsFolder(...o)),class:"btn btn-secondary","aria-label":"Open apps folder"},[HUt,Je(" Open Folder ")]),l("input",{type:"file",onChange:e[2]||(e[2]=(...o)=>r.onFileSelected&&r.onFileSelected(...o)),accept:".zip",ref:"fileInput",style:{display:"none"}},null,544),l("button",{onClick:e[3]||(e[3]=(...o)=>r.triggerFileInput&&r.triggerFileInput(...o)),disabled:i.isUploading,class:"btn-secondary text-green-500 hover:text-green-600 transition duration-300 ease-in-out",title:"Upload App"},X(i.isUploading?"Uploading...":"Upload App"),9,qUt)]),i.message?(T(),w("p",YUt,X(i.message),1)):G("",!0),i.error?(T(),w("p",$Ut,X(i.error),1)):G("",!0),l("div",WUt,[U(l("input",{"onUpdate:modelValue":e[4]||(e[4]=o=>i.searchQuery=o),placeholder:"Search apps...",class:"w-full border-b-2 border-gray-300 px-4 py-2 pl-10 focus:outline-none focus:border-blue-500 transition duration-300 ease-in-out","aria-label":"Search apps"},null,512),[[ue,i.searchQuery]]),KUt])])]),i.loading?(T(),w("div",jUt,ZUt)):G("",!0),(T(!0),w(Ve,null,Ze(r.categories,o=>(T(),w("div",{key:o,class:"mb-12"},[l("h2",JUt,X(o),1),l("div",eFt,[(T(!0),w(Ve,null,Ze(r.filteredApps.filter(a=>a.category===o),a=>(T(),w("div",{key:a.uid,class:"app-card bg-white border rounded-xl shadow-lg p-6 hover:shadow-xl transition duration-300 ease-in-out flex flex-col h-full"},[l("div",tFt,[l("div",nFt,[l("img",{src:a.icon,alt:"App Icon",class:"w-16 h-16 rounded-full border border-gray-300 mr-4"},null,8,sFt),l("div",null,[l("h3",iFt,X(a.name),1),l("p",rFt,"Author: "+X(a.author),1),l("p",oFt,"Version: "+X(a.version),1),l("p",{class:Fe(["text-sm",a.is_public?"text-green-600":"text-orange-600"])},X(a.is_public?"Public App":"Local App"),3)])]),l("div",aFt,[lFt,l("p",cFt,X(a.description),1)]),l("p",dFt,"AI Model: "+X(a.model_name),1),a.disclaimer&&a.disclaimer.trim()!==""?(T(),w("div",uFt,[pFt,l("p",_Ft,X(a.disclaimer),1)])):G("",!0)]),l("div",hFt,[l("div",fFt,[a.installed?(T(),w("button",{key:0,onClick:c=>r.uninstallApp(a.folder_name),class:"text-red-500 hover:text-red-600 transition duration-300 ease-in-out",title:"Uninstall"},bFt,8,mFt)):a.existsInFolder?(T(),w("button",{key:1,onClick:c=>r.deleteApp(a.name),class:"text-yellow-500 hover:text-yellow-600 transition duration-300 ease-in-out",title:"Delete"},vFt,8,EFt)):(T(),w("button",{key:2,onClick:c=>r.installApp(a.folder_name),class:"text-blue-500 hover:text-blue-600 transition duration-300 ease-in-out",title:"Install"},xFt,8,SFt)),a.installed?(T(),w("button",{key:3,onClick:c=>r.editApp(a),class:"text-purple-500 hover:text-purple-600 transition duration-300 ease-in-out",title:"Edit"},RFt,8,CFt)):G("",!0),l("button",{onClick:c=>r.downloadApp(a.folder_name),class:"text-green-500 hover:text-green-600 transition duration-300 ease-in-out",title:"Download"},OFt,8,AFt),l("button",{onClick:c=>r.handleAppClick(a),class:"text-gray-500 hover:text-gray-600 transition duration-300 ease-in-out",title:"View"},DFt,8,IFt),l("button",{onClick:c=>r.openApp(a),class:"text-indigo-500 hover:text-indigo-600 transition duration-300 ease-in-out",title:"Open"},PFt,8,kFt),a.has_server&&a.installed?(T(),w("button",{key:4,onClick:c=>r.startServer(a.folder_name),class:"text-teal-500 hover:text-teal-600 transition duration-300 ease-in-out",title:"Start Server"},BFt,8,UFt)):G("",!0),a.has_update?(T(),w("button",{key:5,onClick:c=>t.updateApp(a.folder_name),class:"relative text-yellow-500 hover:text-yellow-600 transition duration-300 ease-in-out animate-pulse",title:"Update Available"},HFt,8,GFt)):G("",!0)])])]))),128))])]))),128)),i.selectedApp?(T(),w("div",qFt,[l("div",YFt,[l("div",$Ft,[l("h2",WFt,X(i.selectedApp.name),1),l("button",{onClick:e[5]||(e[5]=(...o)=>r.backToZoo&&r.backToZoo(...o)),class:"bg-gray-300 hover:bg-gray-400 px-4 py-2 rounded-lg transition duration-300 ease-in-out"},"Close")]),i.appCode?(T(),w("iframe",{key:0,srcdoc:i.appCode,class:"flex-grow border-none"},null,8,KFt)):(T(),w("p",jFt,"Please install this app to view its code."))])])):G("",!0),i.message?(T(),w("div",{key:2,class:Fe(["fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-md",{"bg-green-100 text-green-800":i.successMessage,"bg-red-100 text-red-800":!i.successMessage}])},X(i.message),3)):G("",!0)])}const XFt=ct(UUt,[["render",QFt]]),ZFt=tP({history:EL("/"),routes:[{path:"/apps_view/",name:"AppsZoo",component:XFt},{path:"/auto_sd_view/",name:"AutoSD",component:PUt},{path:"/comfyui_view/",name:"ComfyUI",component:IUt},{path:"/playground/",name:"playground",component:_et},{path:"/extensions/",name:"extensions",component:Cet},{path:"/help_view/",name:"help_view",component:Iet},{path:"/settings/",name:"settings",component:Fbt},{path:"/training/",name:"training",component:rEt},{path:"/quantizing/",name:"quantizing",component:hEt},{path:"/",name:"discussions",component:Iwt},{path:"/",name:"interactive",component:$Dt},{path:"/",name:"nodes",component:wUt}]});const Ku=aD(pXe);console.log("Loaded main.js");function JFt(t){const e={};for(const n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}const Rs=DD({state(){return{is_rt_on:!1,language:"english",languages:[],currentTheme:"",personality_editor:null,showPersonalityEditor:!1,selectedPersonality:null,currentPersonConfig:{ai_name:"",ai_author:"",ai_category:"",ai_language:"",ai_description:"",ai_conditionning:"",ai_disclaimer:"",ai_icon:null},posts_headers:{accept:"application/json","Content-Type":"application/json"},client_id:"",yesNoDialog:null,universalForm:null,toast:null,news:null,messageBox:null,api_get_req:null,api_post_req:null,startSpeechRecognition:null,ready:!1,loading_infos:"",loading_progress:0,version:"unknown",settingsChanged:!1,isConnected:!1,isModelOk:!1,isGenerating:!1,config:null,mountedPers:null,mountedPersArr:[],bindingsZoo:[],modelsArr:[],selectedModel:null,personalities:[],diskUsage:null,ramUsage:null,vramUsage:null,modelsZoo:[],installedModels:[],installedBindings:[],currentModel:null,currentBinding:null,databases:[]}},mutations:{setisRTOn(t,e){t.is_rt_on=e},setLanguages(t,e){t.languages=e},setLanguage(t,e){t.language=e},setIsReady(t,e){t.ready=e},setIsConnected(t,e){t.isConnected=e},setIsModelOk(t,e){t.isModelOk=e},setIsGenerating(t,e){t.isGenerating=e},setConfig(t,e){t.config=e},setPersonalities(t,e){t.personalities=e},setMountedPers(t,e){t.mountedPers=e},setMountedPersArr(t,e){t.mountedPersArr=e},setbindingsZoo(t,e){t.bindingsZoo=e},setModelsArr(t,e){t.modelsArr=e},setselectedModel(t,e){t.selectedModel=e},setDiskUsage(t,e){t.diskUsage=e},setRamUsage(t,e){t.ramUsage=e},setVramUsage(t,e){t.vramUsage=e},setModelsZoo(t,e){t.modelsZoo=e},setCurrentBinding(t,e){t.currentBinding=e},setCurrentModel(t,e){t.currentModel=e},setDatabases(t,e){t.databases=e},setTheme(t){this.currentTheme=t}},getters:{getisRTOn(t){return t.is_rt_on},getLanguages(t){return t.languages},getLanguage(t){return t.language},getIsConnected(t){return t.isConnected},getIsModelOk(t){return t.isModelOk},getIsGenerating(t){return t.isGenerating},getConfig(t){return t.config},getPersonalities(t){return t.personalities},getMountedPersArr(t){return t.mountedPersArr},getMountedPers(t){return t.mountedPers},getbindingsZoo(t){return t.bindingsZoo},getModelsArr(t){return t.modelsArr},getDiskUsage(t){return t.diskUsage},getRamUsage(t){return t.ramUsage},getVramUsage(t){return t.vramUsage},getDatabasesList(t){return t.databases},getModelsZoo(t){return t.modelsZoo},getCyrrentBinding(t){return t.currentBinding},getCurrentModel(t){return t.currentModel}},actions:{async getVersion(){try{let t=await de.get("/get_lollms_webui_version",{});t&&(this.state.version=t.data,console.log("version res:",t),console.log("version :",this.state.version))}catch{console.log("Coudln't get version")}},async refreshConfig({commit:t}){console.log("Fetching configuration");try{console.log("Fetching configuration with client id: ",this.state.client_id);const e=await _I("get_config",this.state.client_id);e.active_personality_id<0&&(e.active_personality_id=0);let n=e.personalities[e.active_personality_id].split("/");e.personality_category=n[0],e.personality_folder=n[1],console.log("Recovered config"),console.log(e),console.log("Committing config"),console.log(e),console.log(this.state.config),t("setConfig",e)}catch(e){console.log(e.message,"refreshConfig")}},async refreshDatabase({commit:t}){let e=await Gs("list_databases");console.log("databases:",e),t("setDatabases",e)},async fetchisRTOn({commit:t}){const n=(await de.get("/is_rt_on")).data.status;t("setisRTOn",n)},async fetchLanguages({commit:t}){console.log("get_personality_languages_list",this.state.client_id);const e=await de.post("/get_personality_languages_list",{client_id:this.state.client_id});console.log("response",e);const n=e.data;console.log("languages",n),t("setLanguages",n)},async fetchLanguage({commit:t}){console.log("get_personality_language",this.state.client_id);const e=await de.post("/get_personality_language",{client_id:this.state.client_id});console.log("response",e);const n=e.data;console.log("language",n),t("setLanguage",n)},async changeLanguage({commit:t},e){console.log("Changing language to ",e);let n=await de.post("/set_personality_language",{client_id:this.state.client_id,language:e});console.log("get_personality_languages_list",this.state.client_id),n=await de.post("/get_personality_languages_list",{client_id:this.state.client_id}),console.log("response",n);const s=n.data;console.log("languages",s),t("setLanguages",s),n=await de.post("/get_personality_language",{client_id:this.state.client_id}),console.log("response",n);const i=n.data;console.log("language",i),t("setLanguage",i),console.log("Language changed successfully:",n.data.message)},async deleteLanguage({commit:t},e){console.log("Deleting ",e);let n=await de.post("/del_personality_language",{client_id:this.state.client_id,language:e});console.log("get_personality_languages_list",this.state.client_id),n=await de.post("/get_personality_languages_list",{client_id:this.state.client_id}),console.log("response",n);const s=n.data;console.log("languages",s),t("setLanguages",s),n=await de.post("/get_personality_language",{client_id:this.state.client_id}),console.log("response",n);const i=n.data;console.log("language",i),t("setLanguage",i),console.log("Language changed successfully:",n.data.message)},async refreshPersonalitiesZoo({commit:t}){let e=[];const n=await Gs("get_all_personalities"),s=Object.keys(n);console.log("Personalities recovered:"+this.state.config.personalities);for(let i=0;i{let u=!1;for(const h of this.state.config.personalities)if(h.includes(r+"/"+c.folder))if(u=!0,h.includes(":")){const f=h.split(":");c.language=f[1]}else c.language=null;let d={};return d=c,d.category=r,d.full_path=r+"/"+c.folder,d.isMounted=u,d});e.length==0?e=a:e=e.concat(a)}e.sort((i,r)=>i.name.localeCompare(r.name)),t("setPersonalities",e),console.log("Done loading personalities")},refreshMountedPersonalities({commit:t}){this.state.config.active_personality_id<0&&(this.state.config.active_personality_id=0);let e=[];const n=[];for(let s=0;sa.full_path==i||a.full_path==r[0]);if(o>=0){let a=JFt(this.state.personalities[o]);r.length>1&&(a.language=r[1]),a?e.push(a):e.push(this.state.personalities[this.state.personalities.findIndex(c=>c.full_path=="generic/lollms")])}else n.push(s),console.log("Couldn't load personality : ",i)}for(let s=n.length-1;s>=0;s--)console.log("Removing personality : ",this.state.config.personalities[n[s]]),this.state.config.personalities.splice(n[s],1),this.state.config.active_personality_id>n[s]&&(this.state.config.active_personality_id-=1);t("setMountedPersArr",e),this.state.mountedPers=this.state.personalities[this.state.personalities.findIndex(s=>s.full_path==this.state.config.personalities[this.state.config.active_personality_id]||s.full_path+":"+s.language==this.state.config.personalities[this.state.config.active_personality_id])]},async refreshBindings({commit:t}){let e=await Gs("list_bindings");console.log("Loaded bindings zoo :",e),this.state.installedBindings=e.filter(s=>s.installed),console.log("Loaded bindings zoo ",this.state.installedBindings),t("setbindingsZoo",e);const n=e.findIndex(s=>s.name==this.state.config.binding_name);n!=-1&&t("setCurrentBinding",e[n])},async refreshModelsZoo({commit:t}){console.log("Fetching models");const n=(await de.get("/get_available_models")).data.filter(s=>s.variants&&s.variants.length>0);console.log(`get_available_models: ${n}`),t("setModelsZoo",n)},async refreshModelStatus({commit:t}){let e=await Gs("get_model_status");t("setIsModelOk",e.status)},async refreshModels({commit:t}){console.log("Fetching models");let e=await Gs("list_models");console.log(`Found ${e}`);let n=await Gs("get_active_model");console.log("Selected model ",n),n!=null&&t("setselectedModel",n.model),t("setModelsArr",e),console.log("setModelsArr",e),console.log("this.state.modelsZoo",this.state.modelsZoo),this.state.modelsZoo.map(i=>{i.isInstalled=e.includes(i.name)}),this.state.installedModels=this.state.modelsZoo.filter(i=>i.isInstalled);const s=this.state.modelsZoo.findIndex(i=>i.name==this.state.config.model_name);s!=-1&&t("setCurrentModel",this.state.modelsZoo[s])},async refreshDiskUsage({commit:t}){this.state.diskUsage=await Gs("disk_usage")},async refreshRamUsage({commit:t}){this.state.ramUsage=await Gs("ram_usage")},async refreshVramUsage({commit:t}){const e=await Gs("vram_usage"),n=[];if(e.nb_gpus>0){for(let i=0;i!!n.value),onPointerDown:c=>{n.value={x:c.pageX,y:c.pageY},s.value={x:t.value.x,y:t.value.y}},onPointerMove:c=>{if(n.value){const u=c.pageX-n.value.x,d=c.pageY-n.value.y;t.value.x=s.value.x+u/e.value.scaling,t.value.y=s.value.y+d/e.value.scaling}},onPointerUp:()=>{n.value=null,s.value=null}}}function ZO(t,e,n){if(!e.template)return!1;if(Ea(e.template)===n)return!0;const s=t.graphTemplates.find(r=>Ea(r)===n);return s?s.nodes.filter(r=>r.type.startsWith(Gl)).some(r=>ZO(t,e,r.type)):!1}function JO(t){return et(()=>{const e=Array.from(t.value.editor.nodeTypes.entries()),n=new Set(e.map(([,i])=>i.category)),s=[];for(const i of n.values()){let r=e.filter(([,o])=>o.category===i);t.value.displayedGraph.template?r=r.filter(([o])=>!ZO(t.value.editor,t.value.displayedGraph,o)):r=r.filter(([o])=>![ga,ba].includes(o)),r.length>0&&s.push({name:i,nodeTypes:Object.fromEntries(r)})}return s.sort((i,r)=>i.name==="default"?-1:r.name==="default"||i.name>r.name?1:-1),s})}function eI(){const{graph:t}=Bs();return{transform:(n,s)=>{const i=n/t.value.scaling-t.value.panning.x,r=s/t.value.scaling-t.value.panning.y;return[i,r]}}}function okt(){const{graph:t}=Bs();let e=[],n=-1,s={x:0,y:0};const i=et(()=>t.value.panning),r=XO(i),o=et(()=>({"transform-origin":"0 0",transform:`scale(${t.value.scaling}) translate(${t.value.panning.x}px, ${t.value.panning.y}px)`})),a=(m,_,E)=>{const b=[m/t.value.scaling-t.value.panning.x,_/t.value.scaling-t.value.panning.y],g=[m/E-t.value.panning.x,_/E-t.value.panning.y],y=[g[0]-b[0],g[1]-b[1]];t.value.panning.x+=y[0],t.value.panning.y+=y[1],t.value.scaling=E},c=m=>{m.preventDefault();let _=m.deltaY;m.deltaMode===1&&(_*=32);const E=t.value.scaling*(1-_/3e3);a(m.offsetX,m.offsetY,E)},u=()=>({ax:e[0].clientX,ay:e[0].clientY,bx:e[1].clientX,by:e[1].clientY});return{styles:o,...r,onPointerDown:m=>{if(e.push(m),r.onPointerDown(m),e.length===2){const{ax:_,ay:E,bx:b,by:g}=u();s={x:_+(b-_)/2,y:E+(g-E)/2}}},onPointerMove:m=>{for(let _=0;_0){const R=t.value.scaling*(1+(S-n)/500);a(s.x,s.y,R)}n=S}else r.onPointerMove(m)},onPointerUp:m=>{e=e.filter(_=>_.pointerId!==m.pointerId),n=-1,r.onPointerUp()},onMouseWheel:c}}var us=(t=>(t[t.NONE=0]="NONE",t[t.ALLOWED=1]="ALLOWED",t[t.FORBIDDEN=2]="FORBIDDEN",t))(us||{});const tI=Symbol();function akt(){const{graph:t}=Bs(),e=lt(null),n=lt(null),s=a=>{e.value&&(e.value.mx=a.offsetX/t.value.scaling-t.value.panning.x,e.value.my=a.offsetY/t.value.scaling-t.value.panning.y)},i=()=>{if(n.value){if(e.value)return;const a=t.value.connections.find(c=>c.to===n.value);n.value.isInput&&a?(e.value={status:us.NONE,from:a.from},t.value.removeConnection(a)):e.value={status:us.NONE,from:n.value},e.value.mx=void 0,e.value.my=void 0}},r=()=>{if(e.value&&n.value){if(e.value.from===n.value)return;t.value.addConnection(e.value.from,e.value.to)}e.value=null},o=a=>{if(n.value=a??null,a&&e.value){e.value.to=a;const c=t.value.checkConnection(e.value.from,e.value.to);if(e.value.status=c.connectionAllowed?us.ALLOWED:us.FORBIDDEN,c.connectionAllowed){const u=c.connectionsInDanger.map(d=>d.id);t.value.connections.forEach(d=>{u.includes(d.id)&&(d.isInDanger=!0)})}}else!a&&e.value&&(e.value.to=void 0,e.value.status=us.NONE,t.value.connections.forEach(c=>{c.isInDanger=!1}))};return zo(tI,{temporaryConnection:e,hoveredOver:o}),{temporaryConnection:e,onMouseMove:s,onMouseDown:i,onMouseUp:r,hoveredOver:o}}function lkt(t){const e=lt(!1),n=lt(0),s=lt(0),i=JO(t),{transform:r}=eI(),o=et(()=>{let d=[];const h={};for(const m of i.value){const _=Object.entries(m.nodeTypes).map(([E,b])=>({label:b.title,value:"addNode:"+E}));m.name==="default"?d=_:h[m.name]=_}const f=[...Object.entries(h).map(([m,_])=>({label:m,submenu:_}))];return f.length>0&&d.length>0&&f.push({isDivider:!0}),f.push(...d),f}),a=et(()=>t.value.settings.contextMenu.additionalItems.length===0?o.value:[{label:"Add node",submenu:o.value},...t.value.settings.contextMenu.additionalItems.map(d=>"isDivider"in d||"submenu"in d?d:{label:d.label,value:"command:"+d.command,disabled:!t.value.commandHandler.canExecuteCommand(d.command)})]);function c(d){e.value=!0,n.value=d.offsetX,s.value=d.offsetY}function u(d){if(d.startsWith("addNode:")){const h=d.substring(8),f=t.value.editor.nodeTypes.get(h);if(!f)return;const m=Wn(new f.type);t.value.displayedGraph.addNode(m);const[_,E]=r(n.value,s.value);m.position.x=_,m.position.y=E}else if(d.startsWith("command:")){const h=d.substring(8);t.value.commandHandler.canExecuteCommand(h)&&t.value.commandHandler.executeCommand(h)}}return{show:e,x:n,y:s,items:a,open:c,onClick:u}}const ckt=cn({setup(){const{viewModel:t}=vs(),{graph:e}=Bs();return{styles:et(()=>{const s=t.value.settings.background,i=e.value.panning.x*e.value.scaling,r=e.value.panning.y*e.value.scaling,o=e.value.scaling*s.gridSize,a=o/s.gridDivision,c=`${o}px ${o}px, ${o}px ${o}px`,u=e.value.scaling>s.subGridVisibleThreshold?`, ${a}px ${a}px, ${a}px ${a}px`:"";return{backgroundPosition:`left ${i}px top ${r}px`,backgroundSize:`${c} ${u}`}})}}}),dn=(t,e)=>{const n=t.__vccOpts||t;for(const[s,i]of e)n[s]=i;return n};function dkt(t,e,n,s,i,r){return T(),w("div",{class:"background",style:$t(t.styles)},null,4)}const ukt=dn(ckt,[["render",dkt]]);function pkt(t){return mw()?(VI(t),!0):!1}function GE(t){return typeof t=="function"?t():Ct(t)}const nI=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const _kt=Object.prototype.toString,hkt=t=>_kt.call(t)==="[object Object]",Ed=()=>{},fkt=mkt();function mkt(){var t,e;return nI&&((t=window==null?void 0:window.navigator)==null?void 0:t.userAgent)&&(/iP(ad|hone|od)/.test(window.navigator.userAgent)||((e=window==null?void 0:window.navigator)==null?void 0:e.maxTouchPoints)>2&&/iPad|Macintosh/.test(window==null?void 0:window.navigator.userAgent))}function gkt(t,e,n=!1){return e.reduce((s,i)=>(i in t&&(!n||t[i]!==void 0)&&(s[i]=t[i]),s),{})}function bkt(t,e={}){if(!un(t))return SM(t);const n=Array.isArray(t.value)?Array.from({length:t.value.length}):{};for(const s in t.value)n[s]=vM(()=>({get(){return t.value[s]},set(i){var r;if((r=GE(e.replaceRef))!=null?r:!0)if(Array.isArray(t.value)){const a=[...t.value];a[s]=i,t.value=a}else{const a={...t.value,[s]:i};Object.setPrototypeOf(a,Object.getPrototypeOf(t.value)),t.value=a}else t.value[s]=i}}));return n}function al(t){var e;const n=GE(t);return(e=n==null?void 0:n.$el)!=null?e:n}const VE=nI?window:void 0;function yl(...t){let e,n,s,i;if(typeof t[0]=="string"||Array.isArray(t[0])?([n,s,i]=t,e=VE):[e,n,s,i]=t,!e)return Ed;Array.isArray(n)||(n=[n]),Array.isArray(s)||(s=[s]);const r=[],o=()=>{r.forEach(d=>d()),r.length=0},a=(d,h,f,m)=>(d.addEventListener(h,f,m),()=>d.removeEventListener(h,f,m)),c=Mn(()=>[al(e),GE(i)],([d,h])=>{if(o(),!d)return;const f=hkt(h)?{...h}:h;r.push(...n.flatMap(m=>s.map(_=>a(d,m,_,f))))},{immediate:!0,flush:"post"}),u=()=>{c(),o()};return pkt(u),u}let J1=!1;function sI(t,e,n={}){const{window:s=VE,ignore:i=[],capture:r=!0,detectIframe:o=!1}=n;if(!s)return Ed;fkt&&!J1&&(J1=!0,Array.from(s.document.body.children).forEach(f=>f.addEventListener("click",Ed)),s.document.documentElement.addEventListener("click",Ed));let a=!0;const c=f=>i.some(m=>{if(typeof m=="string")return Array.from(s.document.querySelectorAll(m)).some(_=>_===f.target||f.composedPath().includes(_));{const _=al(m);return _&&(f.target===_||f.composedPath().includes(_))}}),d=[yl(s,"click",f=>{const m=al(t);if(!(!m||m===f.target||f.composedPath().includes(m))){if(f.detail===0&&(a=!c(f)),!a){a=!0;return}e(f)}},{passive:!0,capture:r}),yl(s,"pointerdown",f=>{const m=al(t);a=!c(f)&&!!(m&&!f.composedPath().includes(m))},{passive:!0}),o&&yl(s,"blur",f=>{setTimeout(()=>{var m;const _=al(t);((m=s.document.activeElement)==null?void 0:m.tagName)==="IFRAME"&&!(_!=null&&_.contains(s.document.activeElement))&&e(f)},0)})].filter(Boolean);return()=>d.forEach(f=>f())}const iI={x:0,y:0,pointerId:0,pressure:0,tiltX:0,tiltY:0,width:0,height:0,twist:0,pointerType:null},Ekt=Object.keys(iI);function ykt(t={}){const{target:e=VE}=t,n=lt(!1),s=lt(t.initialValue||{});Object.assign(s.value,iI,s.value);const i=r=>{n.value=!0,!(t.pointerTypes&&!t.pointerTypes.includes(r.pointerType))&&(s.value=gkt(r,Ekt,!1))};if(e){const r={passive:!0};yl(e,["pointerdown","pointermove","pointerup"],i,r),yl(e,"pointerleave",()=>n.value=!1,r)}return{...bkt(s),isInside:n}}const vkt=["onMouseenter","onMouseleave","onClick"],Skt={class:"flex-fill"},Tkt={key:0,class:"__submenu-icon",style:{"line-height":"1em"}},xkt=l("svg",{width:"13",height:"13",viewBox:"-60 120 250 250"},[l("path",{d:"M160.875 279.5625 L70.875 369.5625 L70.875 189.5625 L160.875 279.5625 Z",stroke:"none",fill:"white"})],-1),Ckt=[xkt],zE=cn({__name:"ContextMenu",props:{modelValue:{type:Boolean},items:{},x:{default:0},y:{default:0},isNested:{type:Boolean,default:!1},isFlipped:{default:()=>({x:!1,y:!1})},flippable:{type:Boolean,default:!1}},emits:["update:modelValue","click"],setup(t,{emit:e}){const n=t,s=e;let i=null;const r=lt(null),o=lt(-1),a=lt(0),c=lt({x:!1,y:!1}),u=et(()=>n.flippable&&(c.value.x||n.isFlipped.x)),d=et(()=>n.flippable&&(c.value.y||n.isFlipped.y)),h=et(()=>{const y={};return n.isNested||(y.top=(d.value?n.y-a.value:n.y)+"px",y.left=n.x+"px"),y}),f=et(()=>({"--flipped-x":u.value,"--flipped-y":d.value,"--nested":n.isNested})),m=et(()=>n.items.map(y=>({...y,hover:!1})));Mn([()=>n.y,()=>n.items],()=>{var y,v,S,R;a.value=n.items.length*30;const C=((v=(y=r.value)==null?void 0:y.parentElement)==null?void 0:v.offsetWidth)??0,A=((R=(S=r.value)==null?void 0:S.parentElement)==null?void 0:R.offsetHeight)??0;c.value.x=!n.isNested&&n.x>C*.75,c.value.y=!n.isNested&&n.y+a.value>A-20}),sI(r,()=>{n.modelValue&&s("update:modelValue",!1)});const _=y=>{!y.submenu&&y.value&&(s("click",y.value),s("update:modelValue",!1))},E=y=>{s("click",y),o.value=-1,n.isNested||s("update:modelValue",!1)},b=(y,v)=>{n.items[v].submenu&&(o.value=v,i!==null&&(clearTimeout(i),i=null))},g=(y,v)=>{n.items[v].submenu&&(i=window.setTimeout(()=>{o.value=-1,i=null},200))};return(y,v)=>{const S=at("ContextMenu",!0);return T(),wt(Ds,{name:"slide-fade"},{default:We(()=>[U(l("div",{ref_key:"el",ref:r,class:Fe(["baklava-context-menu",f.value]),style:$t(h.value)},[(T(!0),w(Ve,null,Ze(m.value,(R,C)=>(T(),w(Ve,null,[R.isDivider?(T(),w("div",{key:`d-${C}`,class:"divider"})):(T(),w("div",{key:`i-${C}`,class:Fe(["item",{submenu:!!R.submenu,"--disabled":!!R.disabled}]),onMouseenter:A=>b(A,C),onMouseleave:A=>g(A,C),onClick:ae(A=>_(R),["stop","prevent"])},[l("div",Skt,X(R.label),1),R.submenu?(T(),w("div",Tkt,Ckt)):G("",!0),R.submenu?(T(),wt(S,{key:1,"model-value":o.value===C,items:R.submenu,"is-nested":!0,"is-flipped":{x:u.value,y:d.value},flippable:y.flippable,onClick:E},null,8,["model-value","items","is-flipped","flippable"])):G("",!0)],42,vkt))],64))),256))],6),[[xt,y.modelValue]])]),_:1})}}}),wkt={},Rkt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"16",height:"16",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},Akt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),Nkt=l("circle",{cx:"12",cy:"12",r:"1"},null,-1),Okt=l("circle",{cx:"12",cy:"19",r:"1"},null,-1),Ikt=l("circle",{cx:"12",cy:"5",r:"1"},null,-1),Mkt=[Akt,Nkt,Okt,Ikt];function Dkt(t,e){return T(),w("svg",Rkt,Mkt)}const rI=dn(wkt,[["render",Dkt]]),kkt=["id"],Lkt={key:0,class:"__tooltip"},Pkt={key:2,class:"align-middle"},ew=cn({__name:"NodeInterface",props:{node:{},intf:{}},setup(t){const e=(b,g=100)=>{const y=b!=null&&b.toString?b.toString():"";return y.length>g?y.slice(0,g)+"...":y},n=t,{viewModel:s}=vs(),{hoveredOver:i,temporaryConnection:r}=Zn(tI),o=lt(null),a=et(()=>n.intf.connectionCount>0),c=lt(!1),u=et(()=>s.value.settings.displayValueOnHover&&c.value),d=et(()=>({"--input":n.intf.isInput,"--output":!n.intf.isInput,"--connected":a.value})),h=et(()=>n.intf.component&&(!n.intf.isInput||!n.intf.port||n.intf.connectionCount===0)),f=()=>{c.value=!0,i(n.intf)},m=()=>{c.value=!1,i(void 0)},_=()=>{o.value&&s.value.hooks.renderInterface.execute({intf:n.intf,el:o.value})},E=()=>{const b=s.value.displayedGraph.sidebar;b.nodeId=n.node.id,b.optionName=n.intf.name,b.visible=!0};return si(_),Hl(_),(b,g)=>{var y;return T(),w("div",{id:b.intf.id,ref_key:"el",ref:o,class:Fe(["baklava-node-interface",d.value])},[b.intf.port?(T(),w("div",{key:0,class:Fe(["__port",{"--selected":((y=Ct(r))==null?void 0:y.from)===b.intf}]),onPointerover:f,onPointerout:m},[An(b.$slots,"portTooltip",{showTooltip:u.value},()=>[u.value===!0?(T(),w("span",Lkt,X(e(b.intf.value)),1)):G("",!0)])],34)):G("",!0),h.value?(T(),wt(pu(b.intf.component),{key:1,modelValue:b.intf.value,"onUpdate:modelValue":g[0]||(g[0]=v=>b.intf.value=v),node:b.node,intf:b.intf,onOpenSidebar:E},null,40,["modelValue","node","intf"])):(T(),w("span",Pkt,X(b.intf.name),1))],10,kkt)}}}),Ukt=["id","data-node-type"],Fkt={class:"__title-label"},Bkt={class:"__menu"},Gkt={class:"__outputs"},Vkt={class:"__inputs"},zkt=cn({__name:"Node",props:{node:{},selected:{type:Boolean,default:!1},dragging:{type:Boolean}},emits:["select","start-drag"],setup(t,{emit:e}){const n=t,s=e,{viewModel:i}=vs(),{graph:r,switchGraph:o}=Bs(),a=lt(null),c=lt(!1),u=lt(""),d=lt(null),h=lt(!1),f=lt(!1),m=et(()=>{const B=[{value:"rename",label:"Rename"},{value:"delete",label:"Delete"}];return n.node.type.startsWith(Gl)&&B.push({value:"editSubgraph",label:"Edit Subgraph"}),B}),_=et(()=>({"--selected":n.selected,"--dragging":n.dragging,"--two-column":!!n.node.twoColumn})),E=et(()=>{var B,z;return{top:`${((B=n.node.position)==null?void 0:B.y)??0}px`,left:`${((z=n.node.position)==null?void 0:z.x)??0}px`,"--width":`${n.node.width??i.value.settings.nodes.defaultWidth}px`}}),b=et(()=>Object.values(n.node.inputs).filter(B=>!B.hidden)),g=et(()=>Object.values(n.node.outputs).filter(B=>!B.hidden)),y=()=>{s("select")},v=B=>{n.selected||y(),s("start-drag",B)},S=()=>{f.value=!0},R=async B=>{var z;switch(B){case"delete":r.value.removeNode(n.node);break;case"rename":u.value=n.node.title,c.value=!0,await Ue(),(z=d.value)==null||z.focus();break;case"editSubgraph":o(n.node.template);break}},C=()=>{n.node.title=u.value,c.value=!1},A=()=>{a.value&&i.value.hooks.renderNode.execute({node:n.node,el:a.value})},D=B=>{h.value=!0,B.preventDefault()},x=B=>{if(!h.value)return;const z=n.node.width+B.movementX/r.value.scaling,J=i.value.settings.nodes.minWidth,M=i.value.settings.nodes.maxWidth;n.node.width=Math.max(J,Math.min(M,z))},O=()=>{h.value=!1};return si(()=>{A(),window.addEventListener("mousemove",x),window.addEventListener("mouseup",O)}),Hl(A),Ca(()=>{window.removeEventListener("mousemove",x),window.removeEventListener("mouseup",O)}),(B,z)=>(T(),w("div",{id:B.node.id,ref_key:"el",ref:a,class:Fe(["baklava-node",_.value]),style:$t(E.value),"data-node-type":B.node.type,onPointerdown:y},[Ct(i).settings.nodes.resizable?(T(),w("div",{key:0,class:"__resize-handle",onMousedown:D},null,32)):G("",!0),An(B.$slots,"title",{},()=>[l("div",{class:"__title",onPointerdown:ae(v,["self","stop"])},[c.value?U((T(),w("input",{key:1,ref_key:"renameInputEl",ref:d,"onUpdate:modelValue":z[1]||(z[1]=J=>u.value=J),type:"text",class:"baklava-input",placeholder:"Node Name",onBlur:C,onKeydown:ei(C,["enter"])},null,544)),[[ue,u.value]]):(T(),w(Ve,{key:0},[l("div",Fkt,X(B.node.title),1),l("div",Bkt,[he(rI,{class:"--clickable",onClick:S}),he(zE,{modelValue:f.value,"onUpdate:modelValue":z[0]||(z[0]=J=>f.value=J),x:0,y:0,items:m.value,onClick:R},null,8,["modelValue","items"])])],64))],32)]),An(B.$slots,"content",{},()=>[l("div",{class:"__content",onKeydown:z[2]||(z[2]=ei(ae(()=>{},["stop"]),["delete"]))},[l("div",Gkt,[(T(!0),w(Ve,null,Ze(g.value,J=>An(B.$slots,"nodeInterface",{key:J.id,type:"output",node:B.node,intf:J},()=>[he(ew,{node:B.node,intf:J},null,8,["node","intf"])])),128))]),l("div",Vkt,[(T(!0),w(Ve,null,Ze(b.value,J=>An(B.$slots,"nodeInterface",{key:J.id,type:"input",node:B.node,intf:J},()=>[he(ew,{node:B.node,intf:J},null,8,["node","intf"])])),128))])],32)])],46,Ukt))}}),Hkt=cn({props:{x1:{type:Number,required:!0},y1:{type:Number,required:!0},x2:{type:Number,required:!0},y2:{type:Number,required:!0},state:{type:Number,default:us.NONE},isTemporary:{type:Boolean,default:!1}},setup(t){const{viewModel:e}=vs(),{graph:n}=Bs(),s=(o,a)=>{const c=(o+n.value.panning.x)*n.value.scaling,u=(a+n.value.panning.y)*n.value.scaling;return[c,u]},i=et(()=>{const[o,a]=s(t.x1,t.y1),[c,u]=s(t.x2,t.y2);if(e.value.settings.useStraightConnections)return`M ${o} ${a} L ${c} ${u}`;{const d=.3*Math.abs(o-c);return`M ${o} ${a} C ${o+d} ${a}, ${c-d} ${u}, ${c} ${u}`}}),r=et(()=>({"--temporary":t.isTemporary,"--allowed":t.state===us.ALLOWED,"--forbidden":t.state===us.FORBIDDEN}));return{d:i,classes:r}}}),qkt=["d"];function Ykt(t,e,n,s,i,r){return T(),w("path",{class:Fe(["baklava-connection",t.classes]),d:t.d},null,10,qkt)}const oI=dn(Hkt,[["render",Ykt]]);function $kt(t){return document.getElementById(t.id)}function ya(t){const e=document.getElementById(t.id),n=e==null?void 0:e.getElementsByClassName("__port");return{node:(e==null?void 0:e.closest(".baklava-node"))??null,interface:e,port:n&&n.length>0?n[0]:null}}const Wkt=cn({components:{"connection-view":oI},props:{connection:{type:Object,required:!0}},setup(t){const{graph:e}=Bs();let n;const s=lt({x1:0,y1:0,x2:0,y2:0}),i=et(()=>t.connection.isInDanger?us.FORBIDDEN:us.NONE),r=et(()=>{var u;return(u=e.value.findNodeById(t.connection.from.nodeId))==null?void 0:u.position}),o=et(()=>{var u;return(u=e.value.findNodeById(t.connection.to.nodeId))==null?void 0:u.position}),a=u=>u.node&&u.interface&&u.port?[u.node.offsetLeft+u.interface.offsetLeft+u.port.offsetLeft+u.port.clientWidth/2,u.node.offsetTop+u.interface.offsetTop+u.port.offsetTop+u.port.clientHeight/2]:[0,0],c=()=>{const u=ya(t.connection.from),d=ya(t.connection.to);u.node&&d.node&&(n||(n=new ResizeObserver(()=>{c()}),n.observe(u.node),n.observe(d.node)));const[h,f]=a(u),[m,_]=a(d);s.value={x1:h,y1:f,x2:m,y2:_}};return si(async()=>{await Ue(),c()}),Ca(()=>{n&&n.disconnect()}),Mn([r,o],()=>c(),{deep:!0}),{d:s,state:i}}});function Kkt(t,e,n,s,i,r){const o=at("connection-view");return T(),wt(o,{x1:t.d.x1,y1:t.d.y1,x2:t.d.x2,y2:t.d.y2,state:t.state},null,8,["x1","y1","x2","y2","state"])}const jkt=dn(Wkt,[["render",Kkt]]);function Zd(t){return t.node&&t.interface&&t.port?[t.node.offsetLeft+t.interface.offsetLeft+t.port.offsetLeft+t.port.clientWidth/2,t.node.offsetTop+t.interface.offsetTop+t.port.offsetTop+t.port.clientHeight/2]:[0,0]}const Qkt=cn({components:{"connection-view":oI},props:{connection:{type:Object,required:!0}},setup(t){const e=et(()=>t.connection?t.connection.status:us.NONE);return{d:et(()=>{if(!t.connection)return{input:[0,0],output:[0,0]};const s=Zd(ya(t.connection.from)),i=t.connection.to?Zd(ya(t.connection.to)):[t.connection.mx||s[0],t.connection.my||s[1]];return t.connection.from.isInput?{input:i,output:s}:{input:s,output:i}}),status:e}}});function Xkt(t,e,n,s,i,r){const o=at("connection-view");return T(),wt(o,{x1:t.d.input[0],y1:t.d.input[1],x2:t.d.output[0],y2:t.d.output[1],state:t.status,"is-temporary":""},null,8,["x1","y1","x2","y2","state"])}const Zkt=dn(Qkt,[["render",Xkt]]),Jkt=cn({setup(){const{viewModel:t}=vs(),{graph:e}=Bs(),n=lt(null),s=xd(t.value.settings.sidebar,"width"),i=et(()=>t.value.settings.sidebar.resizable),r=et(()=>{const h=e.value.sidebar.nodeId;return e.value.nodes.find(f=>f.id===h)}),o=et(()=>({width:`${s.value}px`})),a=et(()=>r.value?[...Object.values(r.value.inputs),...Object.values(r.value.outputs)].filter(f=>f.displayInSidebar&&f.component):[]),c=()=>{e.value.sidebar.visible=!1},u=()=>{window.addEventListener("mousemove",d),window.addEventListener("mouseup",()=>{window.removeEventListener("mousemove",d)},{once:!0})},d=h=>{var f,m;const _=((m=(f=n.value)==null?void 0:f.parentElement)==null?void 0:m.getBoundingClientRect().width)??500;let E=s.value-h.movementX;E<300?E=300:E>.9*_&&(E=.9*_),s.value=E};return{el:n,graph:e,resizable:i,node:r,styles:o,displayedInterfaces:a,startResize:u,close:c}}}),eLt={class:"__header"},tLt={class:"__node-name"};function nLt(t,e,n,s,i,r){return T(),w("div",{ref:"el",class:Fe(["baklava-sidebar",{"--open":t.graph.sidebar.visible}]),style:$t(t.styles)},[t.resizable?(T(),w("div",{key:0,class:"__resizer",onMousedown:e[0]||(e[0]=(...o)=>t.startResize&&t.startResize(...o))},null,32)):G("",!0),l("div",eLt,[l("button",{tabindex:"-1",class:"__close",onClick:e[1]||(e[1]=(...o)=>t.close&&t.close(...o))},"×"),l("div",tLt,[l("b",null,X(t.node?t.node.title:""),1)])]),(T(!0),w(Ve,null,Ze(t.displayedInterfaces,o=>(T(),w("div",{key:o.id,class:"__interface"},[(T(),wt(pu(o.component),{modelValue:o.value,"onUpdate:modelValue":a=>o.value=a,node:t.node,intf:o},null,8,["modelValue","onUpdate:modelValue","node","intf"]))]))),128))],6)}const sLt=dn(Jkt,[["render",nLt]]),iLt=cn({__name:"Minimap",setup(t){const{viewModel:e}=vs(),{graph:n}=Bs(),s=lt(null),i=lt(!1);let r,o=!1,a={x1:0,y1:0,x2:0,y2:0},c;const u=()=>{var C,A;if(!r)return;r.canvas.width=s.value.offsetWidth,r.canvas.height=s.value.offsetHeight;const D=new Map,x=new Map;for(const M of n.value.nodes){const q=$kt(M),H=(q==null?void 0:q.offsetWidth)??0,P=(q==null?void 0:q.offsetHeight)??0,$=((C=M.position)==null?void 0:C.x)??0,ee=((A=M.position)==null?void 0:A.y)??0;D.set(M,{x1:$,y1:ee,x2:$+H,y2:ee+P}),x.set(M,q)}const O={x1:Number.MAX_SAFE_INTEGER,y1:Number.MAX_SAFE_INTEGER,x2:Number.MIN_SAFE_INTEGER,y2:Number.MIN_SAFE_INTEGER};for(const M of D.values())M.x1O.x2&&(O.x2=M.x2),M.y2>O.y2&&(O.y2=M.y2);const B=50;O.x1-=B,O.y1-=B,O.x2+=B,O.y2+=B,a=O;const z=r.canvas.width/r.canvas.height,J=(a.x2-a.x1)/(a.y2-a.y1);if(z>J){const M=(z-J)*(a.y2-a.y1)*.5;a.x1-=M,a.x2+=M}else{const M=a.x2-a.x1,q=a.y2-a.y1,H=(M-z*q)/z*.5;a.y1-=H,a.y2+=H}r.clearRect(0,0,r.canvas.width,r.canvas.height),r.strokeStyle="white";for(const M of n.value.connections){const[q,H]=Zd(ya(M.from)),[P,$]=Zd(ya(M.to)),[ee,re]=d(q,H),[me,Se]=d(P,$);if(r.beginPath(),r.moveTo(ee,re),e.value.settings.useStraightConnections)r.lineTo(me,Se);else{const le=.3*Math.abs(ee-me);r.bezierCurveTo(ee+le,re,me-le,Se,me,Se)}r.stroke()}r.strokeStyle="lightgray";for(const[M,q]of D.entries()){const[H,P]=d(q.x1,q.y1),[$,ee]=d(q.x2,q.y2);r.fillStyle=f(x.get(M)),r.beginPath(),r.rect(H,P,$-H,ee-P),r.fill(),r.stroke()}if(i.value){const M=_(),[q,H]=d(M.x1,M.y1),[P,$]=d(M.x2,M.y2);r.fillStyle="rgba(255, 255, 255, 0.2)",r.fillRect(q,H,P-q,$-H)}},d=(C,A)=>[(C-a.x1)/(a.x2-a.x1)*r.canvas.width,(A-a.y1)/(a.y2-a.y1)*r.canvas.height],h=(C,A)=>[C*(a.x2-a.x1)/r.canvas.width+a.x1,A*(a.y2-a.y1)/r.canvas.height+a.y1],f=C=>{if(C){const A=C.querySelector(".__content");if(A){const x=m(A);if(x)return x}const D=m(C);if(D)return D}return"gray"},m=C=>{const A=getComputedStyle(C).backgroundColor;if(A&&A!=="rgba(0, 0, 0, 0)")return A},_=()=>{const C=s.value.parentElement.offsetWidth,A=s.value.parentElement.offsetHeight,D=C/n.value.scaling-n.value.panning.x,x=A/n.value.scaling-n.value.panning.y;return{x1:-n.value.panning.x,y1:-n.value.panning.y,x2:D,y2:x}},E=C=>{C.button===0&&(o=!0,b(C))},b=C=>{if(o){const[A,D]=h(C.offsetX,C.offsetY),x=_(),O=(x.x2-x.x1)/2,B=(x.y2-x.y1)/2;n.value.panning.x=-(A-O),n.value.panning.y=-(D-B)}},g=()=>{o=!1},y=()=>{i.value=!0},v=()=>{i.value=!1,g()};Mn([i,n.value.panning,()=>n.value.scaling,()=>n.value.connections.length],()=>{u()});const S=et(()=>n.value.nodes.map(C=>C.position)),R=et(()=>n.value.nodes.map(C=>C.width));return Mn([S,R],()=>{u()},{deep:!0}),si(()=>{r=s.value.getContext("2d"),r.imageSmoothingQuality="high",u(),c=setInterval(u,500)}),Ca(()=>{clearInterval(c)}),(C,A)=>(T(),w("canvas",{ref_key:"canvas",ref:s,class:"baklava-minimap",onMouseenter:y,onMouseleave:v,onMousedown:ae(E,["self"]),onMousemove:ae(b,["self"]),onMouseup:g},null,544))}}),rLt=cn({components:{ContextMenu:zE,VerticalDots:rI},props:{type:{type:String,required:!0},title:{type:String,required:!0}},setup(t){const{viewModel:e}=vs(),{switchGraph:n}=Bs(),s=lt(!1),i=et(()=>t.type.startsWith(Gl));return{showContextMenu:s,hasContextMenu:i,contextMenuItems:[{label:"Edit Subgraph",value:"editSubgraph"},{label:"Delete Subgraph",value:"deleteSubgraph"}],openContextMenu:()=>{s.value=!0},onContextMenuClick:c=>{const u=t.type.substring(Gl.length),d=e.value.editor.graphTemplates.find(h=>h.id===u);if(d)switch(c){case"editSubgraph":n(d);break;case"deleteSubgraph":e.value.editor.removeGraphTemplate(d);break}}}}}),oLt=["data-node-type"],aLt={class:"__title"},lLt={class:"__title-label"},cLt={key:0,class:"__menu"};function dLt(t,e,n,s,i,r){const o=at("vertical-dots"),a=at("context-menu");return T(),w("div",{class:"baklava-node --palette","data-node-type":t.type},[l("div",aLt,[l("div",lLt,X(t.title),1),t.hasContextMenu?(T(),w("div",cLt,[he(o,{class:"--clickable",onPointerdown:e[0]||(e[0]=ae(()=>{},["stop","prevent"])),onClick:ae(t.openContextMenu,["stop","prevent"])},null,8,["onClick"]),he(a,{modelValue:t.showContextMenu,"onUpdate:modelValue":e[1]||(e[1]=c=>t.showContextMenu=c),x:-100,y:0,items:t.contextMenuItems,onClick:t.onContextMenuClick,onPointerdown:e[2]||(e[2]=ae(()=>{},["stop","prevent"]))},null,8,["modelValue","items","onClick"])])):G("",!0)])],8,oLt)}const tw=dn(rLt,[["render",dLt]]),uLt={class:"baklava-node-palette"},pLt={key:0},_Lt=cn({__name:"NodePalette",setup(t){const{viewModel:e}=vs(),{x:n,y:s}=ykt(),{transform:i}=eI(),r=JO(e),o=Zn("editorEl"),a=lt(null),c=et(()=>{if(!a.value||!(o!=null&&o.value))return{};const{left:d,top:h}=o.value.getBoundingClientRect();return{top:`${s.value-h}px`,left:`${n.value-d}px`}}),u=(d,h)=>{a.value={type:d,nodeInformation:h};const f=()=>{const m=Wn(new h.type);e.value.displayedGraph.addNode(m);const _=o.value.getBoundingClientRect(),[E,b]=i(n.value-_.left,s.value-_.top);m.position.x=E,m.position.y=b,a.value=null,document.removeEventListener("pointerup",f)};document.addEventListener("pointerup",f)};return(d,h)=>(T(),w(Ve,null,[l("div",uLt,[(T(!0),w(Ve,null,Ze(Ct(r),f=>(T(),w("section",{key:f.name},[f.name!=="default"?(T(),w("h1",pLt,X(f.name),1)):G("",!0),(T(!0),w(Ve,null,Ze(f.nodeTypes,(m,_)=>(T(),wt(tw,{key:_,type:_,title:m.title,onPointerdown:E=>u(_,m)},null,8,["type","title","onPointerdown"]))),128))]))),128))]),he(Ds,{name:"fade"},{default:We(()=>[a.value?(T(),w("div",{key:0,class:"baklava-dragged-node",style:$t(c.value)},[he(tw,{type:a.value.type,title:a.value.nodeInformation.title},null,8,["type","title"])],4)):G("",!0)]),_:1})],64))}});let id;const hLt=new Uint8Array(16);function fLt(){if(!id&&(id=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!id))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return id(hLt)}const vn=[];for(let t=0;t<256;++t)vn.push((t+256).toString(16).slice(1));function mLt(t,e=0){return vn[t[e+0]]+vn[t[e+1]]+vn[t[e+2]]+vn[t[e+3]]+"-"+vn[t[e+4]]+vn[t[e+5]]+"-"+vn[t[e+6]]+vn[t[e+7]]+"-"+vn[t[e+8]]+vn[t[e+9]]+"-"+vn[t[e+10]]+vn[t[e+11]]+vn[t[e+12]]+vn[t[e+13]]+vn[t[e+14]]+vn[t[e+15]]}const gLt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),nw={randomUUID:gLt};function Jd(t,e,n){if(nw.randomUUID&&!e&&!t)return nw.randomUUID();t=t||{};const s=t.random||(t.rng||fLt)();if(s[6]=s[6]&15|64,s[8]=s[8]&63|128,e){n=n||0;for(let i=0;i<16;++i)e[n+i]=s[i];return e}return mLt(s)}const Vl="SAVE_SUBGRAPH";function bLt(t,e){const n=()=>{const s=t.value;if(!s.template)throw new Error("Graph template property not set");s.template.update(s.save()),s.template.panning=s.panning,s.template.scaling=s.scaling};e.registerCommand(Vl,{canExecute:()=>{var s;return t.value!==((s=t.value.editor)==null?void 0:s.graph)},execute:n})}const ELt={},yLt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},vLt=l("polyline",{points:"6 9 12 15 18 9"},null,-1),SLt=[vLt];function TLt(t,e){return T(),w("svg",yLt,SLt)}const xLt=dn(ELt,[["render",TLt]]),CLt=cn({components:{"i-arrow":xLt},props:{intf:{type:Object,required:!0}},setup(t){const e=lt(null),n=lt(!1),s=et(()=>t.intf.items.find(o=>typeof o=="string"?o===t.intf.value:o.value===t.intf.value)),i=et(()=>s.value?typeof s.value=="string"?s.value:s.value.text:""),r=o=>{t.intf.value=typeof o=="string"?o:o.value};return sI(e,()=>{n.value=!1}),{el:e,open:n,selectedItem:s,selectedText:i,setSelected:r}}}),wLt=["title"],RLt={class:"__selected"},ALt={class:"__text"},NLt={class:"__icon"},OLt={class:"__dropdown"},ILt={class:"item --header"},MLt=["onClick"];function DLt(t,e,n,s,i,r){const o=at("i-arrow");return T(),w("div",{ref:"el",class:Fe(["baklava-select",{"--open":t.open}]),title:t.intf.name,onClick:e[0]||(e[0]=a=>t.open=!t.open)},[l("div",RLt,[l("div",ALt,X(t.selectedText),1),l("div",NLt,[he(o)])]),he(Ds,{name:"slide-fade"},{default:We(()=>[U(l("div",OLt,[l("div",ILt,X(t.intf.name),1),(T(!0),w(Ve,null,Ze(t.intf.items,(a,c)=>(T(),w("div",{key:c,class:Fe(["item",{"--active":a===t.selectedItem}]),onClick:u=>t.setSelected(a)},X(typeof a=="string"?a:a.text),11,MLt))),128))],512),[[xt,t.open]])]),_:1})],10,wLt)}const kLt=dn(CLt,[["render",DLt]]);class LLt extends Xt{constructor(e,n,s){super(e,n),this.component=zl(kLt),this.items=s}}const PLt=cn({props:{intf:{type:Object,required:!0}}});function ULt(t,e,n,s,i,r){return T(),w("div",null,X(t.intf.value),1)}const FLt=dn(PLt,[["render",ULt]]);class BLt extends Xt{constructor(e,n){super(e,n),this.component=zl(FLt),this.setPort(!1)}}const GLt=cn({props:{intf:{type:Object,required:!0},modelValue:{type:String,required:!0}},emits:["update:modelValue"],setup(t,{emit:e}){return{v:et({get:()=>t.modelValue,set:s=>{e("update:modelValue",s)}})}}}),VLt=["placeholder","title"];function zLt(t,e,n,s,i,r){return T(),w("div",null,[U(l("input",{"onUpdate:modelValue":e[0]||(e[0]=o=>t.v=o),type:"text",class:"baklava-input",placeholder:t.intf.name,title:t.intf.name},null,8,VLt),[[ue,t.v]])])}const HLt=dn(GLt,[["render",zLt]]);class tc extends Xt{constructor(){super(...arguments),this.component=zl(HLt)}}class aI extends WO{constructor(){super(...arguments),this._title="Subgraph Input",this.inputs={name:new tc("Name","Input").setPort(!1)},this.outputs={placeholder:new Xt("Connection",void 0)}}}class lI extends KO{constructor(){super(...arguments),this._title="Subgraph Output",this.inputs={name:new tc("Name","Output").setPort(!1),placeholder:new Xt("Connection",void 0)},this.outputs={output:new Xt("Output",void 0).setHidden(!0)}}}const cI="CREATE_SUBGRAPH",sw=[ga,ba];function qLt(t,e,n){const s=()=>t.value.selectedNodes.filter(r=>!sw.includes(r.type)).length>0,i=()=>{const{viewModel:r}=vs(),o=t.value,a=t.value.editor;if(o.selectedNodes.length===0)return;const c=o.selectedNodes.filter(x=>!sw.includes(x.type)),u=c.flatMap(x=>Object.values(x.inputs)),d=c.flatMap(x=>Object.values(x.outputs)),h=o.connections.filter(x=>!d.includes(x.from)&&u.includes(x.to)),f=o.connections.filter(x=>d.includes(x.from)&&!u.includes(x.to)),m=o.connections.filter(x=>d.includes(x.from)&&u.includes(x.to)),_=c.map(x=>x.save()),E=m.map(x=>({id:x.id,from:x.from.id,to:x.to.id})),b=new Map,{xLeft:g,xRight:y,yTop:v}=YLt(c);console.log(g,y,v);for(const[x,O]of h.entries()){const B=new aI;B.inputs.name.value=O.to.name,_.push({...B.save(),position:{x:y-r.value.settings.nodes.defaultWidth-100,y:v+x*200}}),E.push({id:Jd(),from:B.outputs.placeholder.id,to:O.to.id}),b.set(O.to.id,B.graphInterfaceId)}for(const[x,O]of f.entries()){const B=new lI;B.inputs.name.value=O.from.name,_.push({...B.save(),position:{x:g+100,y:v+x*200}}),E.push({id:Jd(),from:O.from.id,to:B.inputs.placeholder.id}),b.set(O.from.id,B.graphInterfaceId)}const S=Wn(new Wu({connections:E,nodes:_,inputs:[],outputs:[]},a));a.addGraphTemplate(S);const R=a.nodeTypes.get(Ea(S));if(!R)throw new Error("Unable to create subgraph: Could not find corresponding graph node type");const C=Wn(new R.type);o.addNode(C);const A=Math.round(c.map(x=>x.position.x).reduce((x,O)=>x+O,0)/c.length),D=Math.round(c.map(x=>x.position.y).reduce((x,O)=>x+O,0)/c.length);C.position.x=A,C.position.y=D,h.forEach(x=>{o.removeConnection(x),o.addConnection(x.from,C.inputs[b.get(x.to.id)])}),f.forEach(x=>{o.removeConnection(x),o.addConnection(C.outputs[b.get(x.from.id)],x.to)}),c.forEach(x=>o.removeNode(x)),e.canExecuteCommand(Vl)&&e.executeCommand(Vl),n(S),t.value.panning={...o.panning},t.value.scaling=o.scaling};e.registerCommand(cI,{canExecute:s,execute:i})}function YLt(t){const e=t.reduce((i,r)=>{const o=r.position.x;return o{const o=r.position.y;return o{const o=r.position.x+r.width;return o>i?o:i},-1/0),xRight:e,yTop:n}}const iw="DELETE_NODES";function $Lt(t,e){e.registerCommand(iw,{canExecute:()=>t.value.selectedNodes.length>0,execute(){t.value.selectedNodes.forEach(n=>t.value.removeNode(n))}}),e.registerHotkey(["Delete"],iw)}const dI="SWITCH_TO_MAIN_GRAPH";function WLt(t,e,n){e.registerCommand(dI,{canExecute:()=>t.value!==t.value.editor.graph,execute:()=>{e.executeCommand(Vl),n(t.value.editor.graph)}})}function KLt(t,e,n){$Lt(t,e),qLt(t,e,n),bLt(t,e),WLt(t,e,n)}class rw{constructor(e,n){this.type=e,e==="addNode"?this.nodeId=n:this.nodeState=n}undo(e){this.type==="addNode"?this.removeNode(e):this.addNode(e)}redo(e){this.type==="addNode"&&this.nodeState?this.addNode(e):this.type==="removeNode"&&this.nodeId&&this.removeNode(e)}addNode(e){const n=e.editor.nodeTypes.get(this.nodeState.type);if(!n)return;const s=new n.type;e.addNode(s),s.load(this.nodeState),this.nodeId=s.id}removeNode(e){const n=e.nodes.find(s=>s.id===this.nodeId);n&&(this.nodeState=n.save(),e.removeNode(n))}}class ow{constructor(e,n){if(this.type=e,e==="addConnection")this.connectionId=n;else{const s=n;this.connectionState={id:s.id,from:s.from.id,to:s.to.id}}}undo(e){this.type==="addConnection"?this.removeConnection(e):this.addConnection(e)}redo(e){this.type==="addConnection"&&this.connectionState?this.addConnection(e):this.type==="removeConnection"&&this.connectionId&&this.removeConnection(e)}addConnection(e){const n=e.findNodeInterface(this.connectionState.from),s=e.findNodeInterface(this.connectionState.to);!n||!s||e.addConnection(n,s)}removeConnection(e){const n=e.connections.find(s=>s.id===this.connectionId);n&&(this.connectionState={id:n.id,from:n.from.id,to:n.to.id},e.removeConnection(n))}}class jLt{constructor(e){if(this.type="transaction",e.length===0)throw new Error("Can't create a transaction with no steps");this.steps=e}undo(e){for(let n=this.steps.length-1;n>=0;n--)this.steps[n].undo(e)}redo(e){for(let n=0;n{if(!r.value)if(a.value)c.value.push(b);else for(o.value!==i.value.length-1&&(i.value=i.value.slice(0,o.value+1)),i.value.push(b),o.value++;i.value.length>s.value;)i.value.shift()},d=()=>{a.value=!0},h=()=>{a.value=!1,c.value.length>0&&(u(new jLt(c.value)),c.value=[])},f=()=>i.value.length!==0&&o.value!==-1,m=()=>{f()&&(r.value=!0,i.value[o.value--].undo(t.value),r.value=!1)},_=()=>i.value.length!==0&&o.value{_()&&(r.value=!0,i.value[++o.value].redo(t.value),r.value=!1)};return Mn(t,(b,g)=>{g&&(g.events.addNode.unsubscribe(n),g.events.removeNode.unsubscribe(n),g.events.addConnection.unsubscribe(n),g.events.removeConnection.unsubscribe(n)),b&&(b.events.addNode.subscribe(n,y=>{u(new rw("addNode",y.id))}),b.events.removeNode.subscribe(n,y=>{u(new rw("removeNode",y.save()))}),b.events.addConnection.subscribe(n,y=>{u(new ow("addConnection",y.id))}),b.events.removeConnection.subscribe(n,y=>{u(new ow("removeConnection",y))}))},{immediate:!0}),e.registerCommand(jg,{canExecute:f,execute:m}),e.registerCommand(Qg,{canExecute:_,execute:E}),e.registerCommand(uI,{canExecute:()=>!a.value,execute:d}),e.registerCommand(pI,{canExecute:()=>a.value,execute:h}),e.registerHotkey(["Control","z"],jg),e.registerHotkey(["Control","y"],Qg),Wn({maxSteps:s})}const Xg="COPY",Zg="PASTE",XLt="CLEAR_CLIPBOARD";function ZLt(t,e,n){const s=Symbol("ClipboardToken"),i=lt(""),r=lt(""),o=et(()=>!i.value),a=()=>{i.value="",r.value=""},c=()=>{const h=t.value.selectedNodes.flatMap(m=>[...Object.values(m.inputs),...Object.values(m.outputs)]),f=t.value.connections.filter(m=>h.includes(m.from)||h.includes(m.to)).map(m=>({from:m.from.id,to:m.to.id}));r.value=JSON.stringify(f),i.value=JSON.stringify(t.value.selectedNodes.map(m=>m.save()))},u=(h,f,m)=>{for(const _ of h){let E;if((!m||m==="input")&&(E=Object.values(_.inputs).find(b=>b.id===f)),!E&&(!m||m==="output")&&(E=Object.values(_.outputs).find(b=>b.id===f)),E)return E}},d=()=>{if(o.value)return;const h=new Map,f=JSON.parse(i.value),m=JSON.parse(r.value),_=[],E=[],b=t.value;n.executeCommand(uI);for(const g of f){const y=e.value.nodeTypes.get(g.type);if(!y){console.warn(`Node type ${g.type} not registered`);return}const v=new y.type,S=v.id;_.push(v),v.hooks.beforeLoad.subscribe(s,R=>{const C=R;return C.position&&(C.position.x+=100,C.position.y+=100),v.hooks.beforeLoad.unsubscribe(s),C}),b.addNode(v),v.load({...g,id:S}),v.id=S,h.set(g.id,S);for(const R of Object.values(v.inputs)){const C=Jd();h.set(R.id,C),R.id=C}for(const R of Object.values(v.outputs)){const C=Jd();h.set(R.id,C),R.id=C}}for(const g of m){const y=u(_,h.get(g.from),"output"),v=u(_,h.get(g.to),"input");if(!y||!v)continue;const S=b.addConnection(y,v);S&&E.push(S)}return t.value.selectedNodes=_,n.executeCommand(pI),{newNodes:_,newConnections:E}};return n.registerCommand(Xg,{canExecute:()=>t.value.selectedNodes.length>0,execute:c}),n.registerHotkey(["Control","c"],Xg),n.registerCommand(Zg,{canExecute:()=>!o.value,execute:d}),n.registerHotkey(["Control","v"],Zg),n.registerCommand(XLt,{canExecute:()=>!0,execute:a}),Wn({isEmpty:o})}const JLt="OPEN_SIDEBAR";function ePt(t,e){e.registerCommand(JLt,{execute:n=>{t.value.sidebar.nodeId=n,t.value.sidebar.visible=!0},canExecute:()=>!0})}function tPt(t,e){ePt(t,e)}const nPt={},sPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},iPt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),rPt=l("path",{d:"M9 13l-4 -4l4 -4m-4 4h11a4 4 0 0 1 0 8h-1"},null,-1),oPt=[iPt,rPt];function aPt(t,e){return T(),w("svg",sPt,oPt)}const lPt=dn(nPt,[["render",aPt]]),cPt={},dPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},uPt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),pPt=l("path",{d:"M15 13l4 -4l-4 -4m4 4h-11a4 4 0 0 0 0 8h1"},null,-1),_Pt=[uPt,pPt];function hPt(t,e){return T(),w("svg",dPt,_Pt)}const fPt=dn(cPt,[["render",hPt]]),mPt={},gPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},bPt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),EPt=l("line",{x1:"5",y1:"12",x2:"19",y2:"12"},null,-1),yPt=l("line",{x1:"5",y1:"12",x2:"11",y2:"18"},null,-1),vPt=l("line",{x1:"5",y1:"12",x2:"11",y2:"6"},null,-1),SPt=[bPt,EPt,yPt,vPt];function TPt(t,e){return T(),w("svg",gPt,SPt)}const xPt=dn(mPt,[["render",TPt]]),CPt={},wPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},RPt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),APt=l("path",{d:"M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2"},null,-1),NPt=l("rect",{x:"9",y:"3",width:"6",height:"4",rx:"2"},null,-1),OPt=[RPt,APt,NPt];function IPt(t,e){return T(),w("svg",wPt,OPt)}const MPt=dn(CPt,[["render",IPt]]),DPt={},kPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},LPt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),PPt=l("rect",{x:"8",y:"8",width:"12",height:"12",rx:"2"},null,-1),UPt=l("path",{d:"M16 8v-2a2 2 0 0 0 -2 -2h-8a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h2"},null,-1),FPt=[LPt,PPt,UPt];function BPt(t,e){return T(),w("svg",kPt,FPt)}const GPt=dn(DPt,[["render",BPt]]),VPt={},zPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},HPt=l("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),qPt=l("path",{d:"M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2"},null,-1),YPt=l("circle",{cx:"12",cy:"14",r:"2"},null,-1),$Pt=l("polyline",{points:"14 4 14 8 8 8 8 4"},null,-1),WPt=[HPt,qPt,YPt,$Pt];function KPt(t,e){return T(),w("svg",zPt,WPt)}const jPt=dn(VPt,[["render",KPt]]),QPt={},XPt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},ZPt=fu('',6),JPt=[ZPt];function eUt(t,e){return T(),w("svg",XPt,JPt)}const tUt=dn(QPt,[["render",eUt]]),nUt=cn({props:{command:{type:String,required:!0},title:{type:String,required:!0},icon:{type:Object,required:!1,default:void 0}},setup(){const{viewModel:t}=vs();return{viewModel:t}}}),sUt=["disabled","title"];function iUt(t,e,n,s,i,r){return T(),w("button",{class:"baklava-toolbar-entry baklava-toolbar-button",disabled:!t.viewModel.commandHandler.canExecuteCommand(t.command),title:t.title,onClick:e[0]||(e[0]=o=>t.viewModel.commandHandler.executeCommand(t.command))},[t.icon?(T(),wt(pu(t.icon),{key:0})):(T(),w(Ve,{key:1},[Je(X(t.title),1)],64))],8,sUt)}const rUt=dn(nUt,[["render",iUt]]),oUt=cn({components:{ToolbarButton:rUt},setup(){const{viewModel:t}=vs();return{isSubgraph:et(()=>t.value.displayedGraph!==t.value.editor.graph),commands:[{command:Xg,title:"Copy",icon:GPt},{command:Zg,title:"Paste",icon:MPt},{command:jg,title:"Undo",icon:lPt},{command:Qg,title:"Redo",icon:fPt},{command:cI,title:"Create Subgraph",icon:tUt}],subgraphCommands:[{command:Vl,title:"Save Subgraph",icon:jPt},{command:dI,title:"Back to Main Graph",icon:xPt}]}}}),aUt={class:"baklava-toolbar"};function lUt(t,e,n,s,i,r){const o=at("toolbar-button");return T(),w("div",aUt,[(T(!0),w(Ve,null,Ze(t.commands,a=>(T(),wt(o,{key:a.command,command:a.command,title:a.title,icon:a.icon},null,8,["command","title","icon"]))),128)),t.isSubgraph?(T(!0),w(Ve,{key:0},Ze(t.subgraphCommands,a=>(T(),wt(o,{key:a.command,command:a.command,title:a.title,icon:a.icon},null,8,["command","title","icon"]))),128)):G("",!0)])}const cUt=dn(oUt,[["render",lUt]]),dUt={class:"connections-container"},uUt=cn({__name:"Editor",props:{viewModel:{}},setup(t){const e=t,n=Symbol("EditorToken"),s=xd(e,"viewModel");rkt(s);const i=lt(null);zo("editorEl",i);const r=et(()=>e.viewModel.displayedGraph.nodes),o=et(()=>e.viewModel.displayedGraph.nodes.map(A=>XO(xd(A,"position")))),a=et(()=>e.viewModel.displayedGraph.connections),c=et(()=>e.viewModel.displayedGraph.selectedNodes),u=okt(),d=akt(),h=lkt(s),f=et(()=>({...u.styles.value})),m=lt(0);e.viewModel.editor.hooks.load.subscribe(n,A=>(m.value++,A));const _=A=>{u.onPointerMove(A),d.onMouseMove(A)},E=A=>{A.button===0&&(A.target===i.value&&(S(),u.onPointerDown(A)),d.onMouseDown())},b=A=>{u.onPointerUp(A),d.onMouseUp()},g=A=>{A.key==="Tab"&&A.preventDefault(),e.viewModel.commandHandler.handleKeyDown(A)},y=A=>{e.viewModel.commandHandler.handleKeyUp(A)},v=A=>{["Control","Shift"].some(D=>e.viewModel.commandHandler.pressedKeys.includes(D))||S(),e.viewModel.displayedGraph.selectedNodes.push(A)},S=()=>{e.viewModel.displayedGraph.selectedNodes=[]},R=A=>{for(const D of e.viewModel.displayedGraph.selectedNodes){const x=r.value.indexOf(D),O=o.value[x];O.onPointerDown(A),document.addEventListener("pointermove",O.onPointerMove)}document.addEventListener("pointerup",C)},C=()=>{for(const A of e.viewModel.displayedGraph.selectedNodes){const D=r.value.indexOf(A),x=o.value[D];x.onPointerUp(),document.removeEventListener("pointermove",x.onPointerMove)}document.removeEventListener("pointerup",C)};return(A,D)=>(T(),w("div",{ref_key:"el",ref:i,tabindex:"-1",class:Fe(["baklava-editor",{"baklava-ignore-mouse":!!Ct(d).temporaryConnection.value||Ct(u).dragging.value,"--temporary-connection":!!Ct(d).temporaryConnection.value}]),onPointermove:ae(_,["self"]),onPointerdown:E,onPointerup:b,onWheel:D[1]||(D[1]=ae((...x)=>Ct(u).onMouseWheel&&Ct(u).onMouseWheel(...x),["self"])),onKeydown:g,onKeyup:y,onContextmenu:D[2]||(D[2]=ae((...x)=>Ct(h).open&&Ct(h).open(...x),["self","prevent"]))},[An(A.$slots,"background",{},()=>[he(ukt)]),An(A.$slots,"toolbar",{},()=>[he(cUt)]),An(A.$slots,"palette",{},()=>[he(_Lt)]),(T(),w("svg",dUt,[(T(!0),w(Ve,null,Ze(a.value,x=>(T(),w("g",{key:x.id+m.value.toString()},[An(A.$slots,"connection",{connection:x},()=>[he(jkt,{connection:x},null,8,["connection"])])]))),128)),An(A.$slots,"temporaryConnection",{temporaryConnection:Ct(d).temporaryConnection.value},()=>[Ct(d).temporaryConnection.value?(T(),wt(Zkt,{key:0,connection:Ct(d).temporaryConnection.value},null,8,["connection"])):G("",!0)])])),l("div",{class:"node-container",style:$t(f.value)},[he(Xs,{name:"fade"},{default:We(()=>[(T(!0),w(Ve,null,Ze(r.value,(x,O)=>An(A.$slots,"node",{key:x.id+m.value.toString(),node:x,selected:c.value.includes(x),dragging:o.value[O].dragging.value,onSelect:B=>v(x),onStartDrag:R},()=>[he(zkt,{node:x,selected:c.value.includes(x),dragging:o.value[O].dragging.value,onSelect:B=>v(x),onStartDrag:R},null,8,["node","selected","dragging","onSelect"])])),128))]),_:3})],4),An(A.$slots,"sidebar",{},()=>[he(sLt)]),An(A.$slots,"minimap",{},()=>[A.viewModel.settings.enableMinimap?(T(),wt(iLt,{key:0})):G("",!0)]),An(A.$slots,"contextMenu",{contextMenu:Ct(h)},()=>[A.viewModel.settings.contextMenu.enabled?(T(),wt(zE,{key:0,modelValue:Ct(h).show.value,"onUpdate:modelValue":D[0]||(D[0]=x=>Ct(h).show.value=x),items:Ct(h).items.value,x:Ct(h).x.value,y:Ct(h).y.value,onClick:Ct(h).onClick},null,8,["modelValue","items","x","y","onClick"])):G("",!0)])],34))}}),pUt=["INPUT","TEXTAREA","SELECT"];function _Ut(t){const e=lt([]),n=lt([]);return{pressedKeys:e,handleKeyDown:o=>{var a;e.value.includes(o.key)||e.value.push(o.key),!pUt.includes(((a=document.activeElement)==null?void 0:a.tagName)??"")&&n.value.forEach(c=>{c.keys.every(u=>e.value.includes(u))&&t(c.commandName)})},handleKeyUp:o=>{const a=e.value.indexOf(o.key);a>=0&&e.value.splice(a,1)},registerHotkey:(o,a)=>{n.value.push({keys:o,commandName:a})}}}const hUt=()=>{const t=lt(new Map),e=(r,o)=>{if(t.value.has(r))throw new Error(`Command "${r}" already exists`);t.value.set(r,o)},n=(r,o=!1,...a)=>{if(!t.value.has(r)){if(o)throw new Error(`[CommandHandler] Command ${r} not registered`);return}return t.value.get(r).execute(...a)},s=(r,o=!1,...a)=>{if(!t.value.has(r)){if(o)throw new Error(`[CommandHandler] Command ${r} not registered`);return!1}return t.value.get(r).canExecute(a)},i=_Ut(n);return Wn({registerCommand:e,executeCommand:n,canExecuteCommand:s,...i})},fUt=t=>!(t instanceof ec);function mUt(t,e){return{switchGraph:s=>{let i;if(fUt(s))i=new ec(t.value),s.createGraph(i);else{if(s!==t.value.graph)throw new Error("Can only switch using 'Graph' instance when it is the root graph. Otherwise a 'GraphTemplate' must be used.");i=s}e.value&&e.value!==t.value.graph&&e.value.destroy(),i.panning=i.panning??s.panning??{x:0,y:0},i.scaling=i.scaling??s.scaling??1,i.selectedNodes=i.selectedNodes??[],i.sidebar=i.sidebar??{visible:!1,nodeId:"",optionName:""},e.value=i}}}function gUt(t,e){t.position=t.position??{x:0,y:0},t.disablePointerEvents=!1,t.twoColumn=t.twoColumn??!1,t.width=t.width??e.defaultWidth}const bUt=()=>({useStraightConnections:!1,enableMinimap:!1,background:{gridSize:100,gridDivision:5,subGridVisibleThreshold:.6},sidebar:{width:300,resizable:!0},displayValueOnHover:!1,nodes:{defaultWidth:200,maxWidth:320,minWidth:150,resizable:!1},contextMenu:{enabled:!0,additionalItems:[]}});function EUt(t){const e=lt(t??new JDt),n=Symbol("ViewModelToken"),s=lt(null),i=mM(s),{switchGraph:r}=mUt(e,s),o=et(()=>i.value&&i.value!==e.value.graph),a=Wn(bUt()),c=hUt(),u=QLt(i,c),d=ZLt(i,e,c),h={renderNode:new ts(null),renderInterface:new ts(null)};return KLt(i,c,r),tPt(i,c),Mn(e,(f,m)=>{m&&(m.events.registerGraph.unsubscribe(n),m.graphEvents.beforeAddNode.unsubscribe(n),f.nodeHooks.beforeLoad.unsubscribe(n),f.nodeHooks.afterSave.unsubscribe(n),f.graphTemplateHooks.beforeLoad.unsubscribe(n),f.graphTemplateHooks.afterSave.unsubscribe(n),f.graph.hooks.load.unsubscribe(n),f.graph.hooks.save.unsubscribe(n)),f&&(f.nodeHooks.beforeLoad.subscribe(n,(_,E)=>(E.position=_.position??{x:0,y:0},E.width=_.width??a.nodes.defaultWidth,E.twoColumn=_.twoColumn??!1,_)),f.nodeHooks.afterSave.subscribe(n,(_,E)=>(_.position=E.position,_.width=E.width,_.twoColumn=E.twoColumn,_)),f.graphTemplateHooks.beforeLoad.subscribe(n,(_,E)=>(E.panning=_.panning,E.scaling=_.scaling,_)),f.graphTemplateHooks.afterSave.subscribe(n,(_,E)=>(_.panning=E.panning,_.scaling=E.scaling,_)),f.graph.hooks.load.subscribe(n,(_,E)=>(E.panning=_.panning,E.scaling=_.scaling,_)),f.graph.hooks.save.subscribe(n,(_,E)=>(_.panning=E.panning,_.scaling=E.scaling,_)),f.graphEvents.beforeAddNode.subscribe(n,_=>gUt(_,{defaultWidth:a.nodes.defaultWidth})),e.value.registerNodeType(aI,{category:"Subgraphs"}),e.value.registerNodeType(lI,{category:"Subgraphs"}),r(f.graph))},{immediate:!0}),Wn({editor:e,displayedGraph:i,isSubgraph:o,settings:a,commandHandler:c,history:u,clipboard:d,hooks:h,switchGraph:r})}const yUt=Ua({type:"PersonalityNode",title:"Personality",inputs:{request:()=>new Xt("Request",""),agent_name:()=>new LLt("Personality","",Rs.state.config.personalities).setPort(!1)},outputs:{response:()=>new Xt("Response","")},async calculate({request:t}){console.log(Rs.state.config.personalities);let e="";try{e=(await de.post("/generate",{params:{text:t}})).data}catch(n){console.error(n)}return{display:e,response:e}}}),vUt=Ua({type:"RAGNode",title:"RAG",inputs:{request:()=>new Xt("Prompt",""),document_path:()=>new tc("Document path","").setPort(!1)},outputs:{prompt:()=>new Xt("Prompt with Data","")},async calculate({request:t,document_path:e}){let n="";try{n=(await de.get("/rag",{params:{text:t,doc_path:e}})).data}catch(s){console.error(s)}return{response:n}}}),aw=Ua({type:"Task",title:"Task",inputs:{description:()=>new tc("Task description","").setPort(!1)},outputs:{prompt:()=>new Xt("Prompt")},calculate({description:t}){return{prompt:t}}}),lw=Ua({type:"TextDisplayNode",title:"TextDisplay",inputs:{text2display:()=>new Xt("Input","")},outputs:{response:()=>new BLt("Text","")},async calculate({request:t}){}}),cw=Ua({type:"LLMNode",title:"LLM",inputs:{request:()=>new Xt("Request","")},outputs:{response:()=>new Xt("Response","")},async calculate({request:t}){console.log(Rs.state.config.personalities);let e="";try{e=(await de.post("/generate",{params:{text:t}})).data}catch(n){console.error(n)}return{display:e,response:e}}}),SUt=Ua({type:"MultichoiceNode",title:"Multichoice",inputs:{question:()=>new Xt("Question",""),outputs:()=>new tc("choices, one per line","","").setPort(!1)},outputs:{response:()=>new Xt("Response","")}}),TUt=cn({components:{"baklava-editor":uUt},setup(){const t=EUt(),e=new ikt(t.editor);t.editor.registerNodeType(yUt),t.editor.registerNodeType(aw),t.editor.registerNodeType(vUt),t.editor.registerNodeType(lw),t.editor.registerNodeType(cw),t.editor.registerNodeType(SUt);const n=Symbol();e.events.afterRun.subscribe(n,a=>{e.pause(),ekt(a,t.editor),e.resume()}),e.start();function s(a,c,u){const d=new a;return t.displayedGraph.addNode(d),d.position.x=c,d.position.y=u,d}const i=s(aw,300,140),r=s(cw,550,140),o=s(lw,850,140);return t.displayedGraph.addConnection(i.outputs.prompt,r.inputs.request),t.displayedGraph.addConnection(r.outputs.response,o.inputs.text2display),{baklava:t,saveGraph:()=>{const a=e.export();localStorage.setItem("myGraph",JSON.stringify(a))},loadGraph:()=>{const a=JSON.parse(localStorage.getItem("myGraph"));e.import(a)}}}}),xUt={style:{width:"100vw",height:"100vh"}};function CUt(t,e,n,s,i,r){const o=at("baklava-editor");return T(),w("div",xUt,[he(o,{"view-model":t.baklava},null,8,["view-model"]),l("button",{onClick:e[0]||(e[0]=(...a)=>t.saveGraph&&t.saveGraph(...a))},"Save Graph"),l("button",{onClick:e[1]||(e[1]=(...a)=>t.loadGraph&&t.loadGraph(...a))},"Load Graph")])}const wUt=ct(TUt,[["render",CUt]]),RUt={},AUt={style:{width:"100vw",height:"100vh"}},NUt=["src"];function OUt(t,e,n,s,i,r){return T(),w("div",AUt,[l("iframe",{src:t.$store.state.config.comfyui_base_url,class:"m-0 p-0 w-full h-full"},null,8,NUt)])}const IUt=ct(RUt,[["render",OUt]]),MUt={},DUt={style:{width:"100vw",height:"100vh"}},kUt=["src"];function LUt(t,e,n,s,i,r){return T(),w("div",DUt,[l("iframe",{src:t.$store.state.config.sd_base_url,class:"m-0 p-0 w-full h-full"},null,8,kUt)])}const PUt=ct(MUt,[["render",LUt]]),UUt={data(){return{apps:[],githubApps:[],selectedApp:null,appCode:"",loading:!1,message:"",successMessage:!0,searchQuery:"",selectedFile:null,isUploading:!1,message:"",error:""}},computed:{combinedApps(){this.apps.map(e=>e.name);const t=new Map(this.apps.map(e=>[e.name,{...e,installed:!0,existsInFolder:!0}]));return this.githubApps.forEach(e=>{t.has(e.name)||t.set(e.name,{...e,installed:!1,existsInFolder:!1})}),Array.from(t.values())},filteredApps(){return this.combinedApps.filter(t=>t.name.toLowerCase().includes(this.searchQuery.toLowerCase())||t.description.toLowerCase().includes(this.searchQuery.toLowerCase()))},categories(){return[...new Set(this.combinedApps.map(t=>t.category))]}},methods:{startServer(t){const e={client_id:this.$store.state.client_id,app_name:t};this.$store.state.messageBox.showBlockingMessage(`Loading server. +This may take some time the first time as some libraries need to be installed.`),de.post("/apps/start_server",e).then(n=>{this.$store.state.messageBox.hideBlockingMessage(),console.log("Server start initiated:",n.data.message),this.$notify({type:"success",title:"Server Starting",text:n.data.message})}).catch(n=>{var s,i;this.$store.state.messageBox.hideBlockingMessage(),console.error("Error starting server:",n),this.$notify({type:"error",title:"Server Start Failed",text:((i=(s=n.response)==null?void 0:s.data)==null?void 0:i.detail)||"An error occurred while starting the server"})})},triggerFileInput(){this.$refs.fileInput.click()},onFileSelected(t){this.selectedFile=t.target.files[0],this.message="",this.error="",this.uploadApp()},async uploadApp(){var e,n;if(!this.selectedFile){this.error="Please select a file to upload.";return}this.isUploading=!0,this.message="",this.error="";const t=new FormData;t.append("file",this.selectedFile),t.append("client_id",this.$store.state.client_id);try{const s=await de.post("/upload_app",t,{headers:{"Content-Type":"multipart/form-data"}});this.message=s.data.message,this.$refs.fileInput.value="",this.selectedFile=null}catch(s){console.error("Error uploading app:",s),this.error=((n=(e=s.response)==null?void 0:e.data)==null?void 0:n.detail)||"Failed to upload the app. Please try again."}finally{this.isUploading=!1}},async fetchApps(){this.loading=!0;try{const t=await de.get("/apps");this.apps=t.data,this.showMessage("Refresh successful!",!0)}catch{this.showMessage("Failed to refresh apps.",!1)}finally{this.loading=!1}},async openAppsFolder(){this.loading=!0;try{console.log("opening apps folder");const t=await de.post("/show_apps_folder",{client_id:this.$store.state.client_id})}catch{this.showMessage("Failed to open apps folder.",!1)}finally{this.loading=!1}},async fetchGithubApps(){this.loading=!0;try{const t=await de.get("/github/apps");this.githubApps=t.data.apps,await this.fetchApps()}catch{this.showMessage("Failed to refresh GitHub apps.",!1)}finally{this.loading=!1}},async handleAppClick(t){if(t.installed){this.selectedApp=t;const e=await de.get(`/apps/${t.folder_name}/index.html`);this.appCode=e.data}else this.showMessage(`Please install ${t.folder_name} to view its code.`,!1)},backToZoo(){this.selectedApp=null,this.appCode=""},async installApp(t){this.loading=!0;try{await de.post(`/install/${t}`,{client_id:this.$store.state.client_id}),this.showMessage("Installation succeeded!",!0)}catch{this.showMessage("Installation failed.",!1)}finally{this.loading=!1,this.fetchApps(),this.fetchGithubApps()}},async uninstallApp(t){this.loading=!0;try{await de.post(`/uninstall/${t}`,{client_id:this.$store.state.client_id}),this.showMessage("Uninstallation succeeded!",!0)}catch{this.showMessage("Uninstallation failed.",!1)}finally{this.loading=!1,this.fetchApps()}},async deleteApp(t){this.loading=!0;try{await de.post(`/delete/${t}`,{client_id:this.$store.state.client_id}),this.showMessage("Deletion succeeded!",!0)}catch{this.showMessage("Deletion failed.",!1)}finally{this.loading=!1,this.fetchApps()}},async editApp(t){this.loading=!0;try{const e=await de.post("/open_app_in_vscode",{client_id:this.$store.state.client_id,app_name:t.folder_name});this.showMessage(e.data.message,!0)}catch{this.showMessage("Failed to open folder in VSCode.",!1)}finally{this.loading=!1}},async downloadApp(t){this.isLoading=!0,this.error=null;try{const e=await de.post("/download_app",{client_id:this.$store.state.client_id,app_name:t}),n=e.headers["content-disposition"],s=n&&n.match(/filename="?(.+)"?/i),i=s?s[1]:"app.zip",r=new Blob([e.data],{type:"application/zip"}),o=window.URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=o,a.download=i,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o),document.body.removeChild(a)}catch(e){console.error("Error downloading app:",e),this.error="Failed to download the app. Please try again."}finally{this.isLoading=!1}},openApp(t){t.installed?window.open(`/apps/${t.folder_name}/index.html?client_id=${this.$store.state.client_id}`,"_blank"):this.showMessage(`Please install ${t.name} before opening.`,!1)},showMessage(t,e){this.message=t,this.successMessage=e,setTimeout(()=>{this.message=""},3e3)}},mounted(){this.fetchGithubApps()}},FUt={class:"app-zoo background-color w-full p-6 overflow-y-auto scrollbar-thin scrollbar-track-bg-light-tone scrollbar-thumb-bg-light-tone-panel hover:scrollbar-thumb-primary dark:scrollbar-track-bg-dark-tone dark:scrollbar-thumb-bg-dark-tone-panel dark:hover:scrollbar-thumb-primary active:scrollbar-thumb-secondary"},BUt={class:"panels-color shadow-lg rounded-lg p-4 max-w-4xl mx-auto"},GUt={class:"flex flex-wrap items-center justify-between gap-4"},VUt={class:"flex items-center space-x-4"},zUt=l("svg",{class:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})],-1),HUt=l("svg",{class:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M5 19a2 2 0 01-2-2V7a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1M5 19h14a2 2 0 002-2v-5a2 2 0 00-2-2H9a2 2 0 00-2 2v5a2 2 0 01-2 2z"})],-1),qUt=["disabled"],YUt={key:0},$Ut={key:1,class:"error"},WUt={class:"relative flex-grow max-w-md"},KUt=l("svg",{class:"w-5 h-5 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})],-1),jUt={key:0,class:"flex justify-center items-center space-x-2 my-8","aria-live":"polite"},QUt=l("div",{class:"animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-blue-500"},null,-1),XUt=l("span",{class:"text-xl text-gray-700 font-semibold"},"Loading...",-1),ZUt=[QUt,XUt],JUt={class:"text-3xl font-bold mb-6 text-gray-800"},eFt={class:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8"},tFt={class:"flex-grow"},nFt={class:"flex items-center mb-4"},sFt=["src"],iFt={class:"font-bold text-xl text-gray-800"},rFt={class:"text-sm text-gray-600"},oFt={class:"text-sm text-gray-600"},aFt={class:"mb-4"},lFt=l("h4",{class:"font-semibold mb-1 text-gray-700"},"Description:",-1),cFt={class:"text-sm text-gray-600 h-20 overflow-y-auto"},dFt={class:"text-sm text-gray-600 mb-2"},uFt={key:0,class:"mb-4"},pFt=l("h4",{class:"font-semibold mb-1 text-gray-700"},"Disclaimer:",-1),_Ft={class:"text-xs text-gray-500 italic h-16 overflow-y-auto"},hFt={class:"mt-auto pt-4 border-t"},fFt={class:"flex justify-between items-center flex-wrap"},mFt=["onClick"],gFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})],-1),bFt=[gFt],EFt=["onClick"],yFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})],-1),vFt=[yFt],SFt=["onClick"],TFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})],-1),xFt=[TFt],CFt=["onClick"],wFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})],-1),RFt=[wFt],AFt=["onClick"],NFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})],-1),OFt=[NFt],IFt=["onClick"],MFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})],-1),DFt=[MFt],kFt=["onClick"],LFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})],-1),PFt=[LFt],UFt=["onClick"],FFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M5 12h14M12 5l7 7-7 7"})],-1),BFt=[FFt],GFt=["onClick"],VFt=l("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[l("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})],-1),zFt=l("span",{class:"absolute top-0 right-0 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-red-100 transform translate-x-1/2 -translate-y-1/2 bg-red-600 rounded-full"},"!",-1),HFt=[VFt,zFt],qFt={key:1,class:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"},YFt={class:"bg-white rounded-lg p-6 w-11/12 h-5/6 flex flex-col"},$Ft={class:"flex justify-between items-center mb-4"},WFt={class:"text-2xl font-bold"},KFt=["srcdoc"],jFt={key:1,class:"text-center text-red-500"};function QFt(t,e,n,s,i,r){return T(),w("div",FUt,[l("nav",BUt,[l("div",GUt,[l("div",VUt,[l("button",{onClick:e[0]||(e[0]=(...o)=>r.fetchGithubApps&&r.fetchGithubApps(...o)),class:"btn btn-primary","aria-label":"Refresh apps from GitHub"},[zUt,Je(" Refresh ")]),l("button",{onClick:e[1]||(e[1]=(...o)=>r.openAppsFolder&&r.openAppsFolder(...o)),class:"btn btn-secondary","aria-label":"Open apps folder"},[HUt,Je(" Open Folder ")]),l("input",{type:"file",onChange:e[2]||(e[2]=(...o)=>r.onFileSelected&&r.onFileSelected(...o)),accept:".zip",ref:"fileInput",style:{display:"none"}},null,544),l("button",{onClick:e[3]||(e[3]=(...o)=>r.triggerFileInput&&r.triggerFileInput(...o)),disabled:i.isUploading,class:"btn-secondary text-green-500 hover:text-green-600 transition duration-300 ease-in-out",title:"Upload App"},X(i.isUploading?"Uploading...":"Upload App"),9,qUt)]),i.message?(T(),w("p",YUt,X(i.message),1)):G("",!0),i.error?(T(),w("p",$Ut,X(i.error),1)):G("",!0),l("div",WUt,[U(l("input",{"onUpdate:modelValue":e[4]||(e[4]=o=>i.searchQuery=o),placeholder:"Search apps...",class:"w-full border-b-2 border-gray-300 px-4 py-2 pl-10 focus:outline-none focus:border-blue-500 transition duration-300 ease-in-out","aria-label":"Search apps"},null,512),[[ue,i.searchQuery]]),KUt])])]),i.loading?(T(),w("div",jUt,ZUt)):G("",!0),(T(!0),w(Ve,null,Ze(r.categories,o=>(T(),w("div",{key:o,class:"mb-12"},[l("h2",JUt,X(o),1),l("div",eFt,[(T(!0),w(Ve,null,Ze(r.filteredApps.filter(a=>a.category===o),a=>(T(),w("div",{key:a.uid,class:"app-card bg-white border rounded-xl shadow-lg p-6 hover:shadow-xl transition duration-300 ease-in-out flex flex-col h-full"},[l("div",tFt,[l("div",nFt,[l("img",{src:a.icon,alt:"App Icon",class:"w-16 h-16 rounded-full border border-gray-300 mr-4"},null,8,sFt),l("div",null,[l("h3",iFt,X(a.name),1),l("p",rFt,"Author: "+X(a.author),1),l("p",oFt,"Version: "+X(a.version),1),l("p",{class:Fe(["text-sm",a.is_public?"text-green-600":"text-orange-600"])},X(a.is_public?"Public App":"Local App"),3)])]),l("div",aFt,[lFt,l("p",cFt,X(a.description),1)]),l("p",dFt,"AI Model: "+X(a.model_name),1),a.disclaimer&&a.disclaimer.trim()!==""?(T(),w("div",uFt,[pFt,l("p",_Ft,X(a.disclaimer),1)])):G("",!0)]),l("div",hFt,[l("div",fFt,[a.installed?(T(),w("button",{key:0,onClick:c=>r.uninstallApp(a.folder_name),class:"text-red-500 hover:text-red-600 transition duration-300 ease-in-out",title:"Uninstall"},bFt,8,mFt)):a.existsInFolder?(T(),w("button",{key:1,onClick:c=>r.deleteApp(a.name),class:"text-yellow-500 hover:text-yellow-600 transition duration-300 ease-in-out",title:"Delete"},vFt,8,EFt)):(T(),w("button",{key:2,onClick:c=>r.installApp(a.folder_name),class:"text-blue-500 hover:text-blue-600 transition duration-300 ease-in-out",title:"Install"},xFt,8,SFt)),a.installed?(T(),w("button",{key:3,onClick:c=>r.editApp(a),class:"text-purple-500 hover:text-purple-600 transition duration-300 ease-in-out",title:"Edit"},RFt,8,CFt)):G("",!0),l("button",{onClick:c=>r.downloadApp(a.folder_name),class:"text-green-500 hover:text-green-600 transition duration-300 ease-in-out",title:"Download"},OFt,8,AFt),l("button",{onClick:c=>r.handleAppClick(a),class:"text-gray-500 hover:text-gray-600 transition duration-300 ease-in-out",title:"View"},DFt,8,IFt),a.installed?(T(),w("button",{key:4,onClick:c=>r.openApp(a),class:"text-indigo-500 hover:text-indigo-600 transition duration-300 ease-in-out",title:"Open"},PFt,8,kFt)):G("",!0),a.has_server&&a.installed?(T(),w("button",{key:5,onClick:c=>r.startServer(a.folder_name),class:"text-teal-500 hover:text-teal-600 transition duration-300 ease-in-out",title:"Start Server"},BFt,8,UFt)):G("",!0),a.has_update?(T(),w("button",{key:6,onClick:c=>t.updateApp(a.folder_name),class:"relative text-yellow-500 hover:text-yellow-600 transition duration-300 ease-in-out animate-pulse",title:"Update Available"},HFt,8,GFt)):G("",!0)])])]))),128))])]))),128)),i.selectedApp?(T(),w("div",qFt,[l("div",YFt,[l("div",$Ft,[l("h2",WFt,X(i.selectedApp.name),1),l("button",{onClick:e[5]||(e[5]=(...o)=>r.backToZoo&&r.backToZoo(...o)),class:"bg-gray-300 hover:bg-gray-400 px-4 py-2 rounded-lg transition duration-300 ease-in-out"},"Close")]),i.appCode?(T(),w("iframe",{key:0,srcdoc:i.appCode,class:"flex-grow border-none"},null,8,KFt)):(T(),w("p",jFt,"Please install this app to view its code."))])])):G("",!0),i.message?(T(),w("div",{key:2,class:Fe(["fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-md",{"bg-green-100 text-green-800":i.successMessage,"bg-red-100 text-red-800":!i.successMessage}])},X(i.message),3)):G("",!0)])}const XFt=ct(UUt,[["render",QFt]]),ZFt=tP({history:EL("/"),routes:[{path:"/apps_view/",name:"AppsZoo",component:XFt},{path:"/auto_sd_view/",name:"AutoSD",component:PUt},{path:"/comfyui_view/",name:"ComfyUI",component:IUt},{path:"/playground/",name:"playground",component:_et},{path:"/extensions/",name:"extensions",component:Cet},{path:"/help_view/",name:"help_view",component:Iet},{path:"/settings/",name:"settings",component:Fbt},{path:"/training/",name:"training",component:rEt},{path:"/quantizing/",name:"quantizing",component:hEt},{path:"/",name:"discussions",component:Iwt},{path:"/",name:"interactive",component:$Dt},{path:"/",name:"nodes",component:wUt}]});const Ku=aD(pXe);console.log("Loaded main.js");function JFt(t){const e={};for(const n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}const Rs=DD({state(){return{is_rt_on:!1,language:"english",languages:[],currentTheme:"",personality_editor:null,showPersonalityEditor:!1,selectedPersonality:null,currentPersonConfig:{ai_name:"",ai_author:"",ai_category:"",ai_language:"",ai_description:"",ai_conditionning:"",ai_disclaimer:"",ai_icon:null},posts_headers:{accept:"application/json","Content-Type":"application/json"},client_id:"",yesNoDialog:null,universalForm:null,toast:null,news:null,messageBox:null,api_get_req:null,api_post_req:null,startSpeechRecognition:null,ready:!1,loading_infos:"",loading_progress:0,version:"unknown",settingsChanged:!1,isConnected:!1,isModelOk:!1,isGenerating:!1,config:null,mountedPers:null,mountedPersArr:[],bindingsZoo:[],modelsArr:[],selectedModel:null,personalities:[],diskUsage:null,ramUsage:null,vramUsage:null,modelsZoo:[],installedModels:[],installedBindings:[],currentModel:null,currentBinding:null,databases:[]}},mutations:{setisRTOn(t,e){t.is_rt_on=e},setLanguages(t,e){t.languages=e},setLanguage(t,e){t.language=e},setIsReady(t,e){t.ready=e},setIsConnected(t,e){t.isConnected=e},setIsModelOk(t,e){t.isModelOk=e},setIsGenerating(t,e){t.isGenerating=e},setConfig(t,e){t.config=e},setPersonalities(t,e){t.personalities=e},setMountedPers(t,e){t.mountedPers=e},setMountedPersArr(t,e){t.mountedPersArr=e},setbindingsZoo(t,e){t.bindingsZoo=e},setModelsArr(t,e){t.modelsArr=e},setselectedModel(t,e){t.selectedModel=e},setDiskUsage(t,e){t.diskUsage=e},setRamUsage(t,e){t.ramUsage=e},setVramUsage(t,e){t.vramUsage=e},setModelsZoo(t,e){t.modelsZoo=e},setCurrentBinding(t,e){t.currentBinding=e},setCurrentModel(t,e){t.currentModel=e},setDatabases(t,e){t.databases=e},setTheme(t){this.currentTheme=t}},getters:{getisRTOn(t){return t.is_rt_on},getLanguages(t){return t.languages},getLanguage(t){return t.language},getIsConnected(t){return t.isConnected},getIsModelOk(t){return t.isModelOk},getIsGenerating(t){return t.isGenerating},getConfig(t){return t.config},getPersonalities(t){return t.personalities},getMountedPersArr(t){return t.mountedPersArr},getMountedPers(t){return t.mountedPers},getbindingsZoo(t){return t.bindingsZoo},getModelsArr(t){return t.modelsArr},getDiskUsage(t){return t.diskUsage},getRamUsage(t){return t.ramUsage},getVramUsage(t){return t.vramUsage},getDatabasesList(t){return t.databases},getModelsZoo(t){return t.modelsZoo},getCyrrentBinding(t){return t.currentBinding},getCurrentModel(t){return t.currentModel}},actions:{async getVersion(){try{let t=await de.get("/get_lollms_webui_version",{});t&&(this.state.version=t.data,console.log("version res:",t),console.log("version :",this.state.version))}catch{console.log("Coudln't get version")}},async refreshConfig({commit:t}){console.log("Fetching configuration");try{console.log("Fetching configuration with client id: ",this.state.client_id);const e=await _I("get_config",this.state.client_id);e.active_personality_id<0&&(e.active_personality_id=0);let n=e.personalities[e.active_personality_id].split("/");e.personality_category=n[0],e.personality_folder=n[1],console.log("Recovered config"),console.log(e),console.log("Committing config"),console.log(e),console.log(this.state.config),t("setConfig",e)}catch(e){console.log(e.message,"refreshConfig")}},async refreshDatabase({commit:t}){let e=await Gs("list_databases");console.log("databases:",e),t("setDatabases",e)},async fetchisRTOn({commit:t}){const n=(await de.get("/is_rt_on")).data.status;t("setisRTOn",n)},async fetchLanguages({commit:t}){console.log("get_personality_languages_list",this.state.client_id);const e=await de.post("/get_personality_languages_list",{client_id:this.state.client_id});console.log("response",e);const n=e.data;console.log("languages",n),t("setLanguages",n)},async fetchLanguage({commit:t}){console.log("get_personality_language",this.state.client_id);const e=await de.post("/get_personality_language",{client_id:this.state.client_id});console.log("response",e);const n=e.data;console.log("language",n),t("setLanguage",n)},async changeLanguage({commit:t},e){console.log("Changing language to ",e);let n=await de.post("/set_personality_language",{client_id:this.state.client_id,language:e});console.log("get_personality_languages_list",this.state.client_id),n=await de.post("/get_personality_languages_list",{client_id:this.state.client_id}),console.log("response",n);const s=n.data;console.log("languages",s),t("setLanguages",s),n=await de.post("/get_personality_language",{client_id:this.state.client_id}),console.log("response",n);const i=n.data;console.log("language",i),t("setLanguage",i),console.log("Language changed successfully:",n.data.message)},async deleteLanguage({commit:t},e){console.log("Deleting ",e);let n=await de.post("/del_personality_language",{client_id:this.state.client_id,language:e});console.log("get_personality_languages_list",this.state.client_id),n=await de.post("/get_personality_languages_list",{client_id:this.state.client_id}),console.log("response",n);const s=n.data;console.log("languages",s),t("setLanguages",s),n=await de.post("/get_personality_language",{client_id:this.state.client_id}),console.log("response",n);const i=n.data;console.log("language",i),t("setLanguage",i),console.log("Language changed successfully:",n.data.message)},async refreshPersonalitiesZoo({commit:t}){let e=[];const n=await Gs("get_all_personalities"),s=Object.keys(n);console.log("Personalities recovered:"+this.state.config.personalities);for(let i=0;i{let u=!1;for(const h of this.state.config.personalities)if(h.includes(r+"/"+c.folder))if(u=!0,h.includes(":")){const f=h.split(":");c.language=f[1]}else c.language=null;let d={};return d=c,d.category=r,d.full_path=r+"/"+c.folder,d.isMounted=u,d});e.length==0?e=a:e=e.concat(a)}e.sort((i,r)=>i.name.localeCompare(r.name)),t("setPersonalities",e),console.log("Done loading personalities")},refreshMountedPersonalities({commit:t}){this.state.config.active_personality_id<0&&(this.state.config.active_personality_id=0);let e=[];const n=[];for(let s=0;sa.full_path==i||a.full_path==r[0]);if(o>=0){let a=JFt(this.state.personalities[o]);r.length>1&&(a.language=r[1]),a?e.push(a):e.push(this.state.personalities[this.state.personalities.findIndex(c=>c.full_path=="generic/lollms")])}else n.push(s),console.log("Couldn't load personality : ",i)}for(let s=n.length-1;s>=0;s--)console.log("Removing personality : ",this.state.config.personalities[n[s]]),this.state.config.personalities.splice(n[s],1),this.state.config.active_personality_id>n[s]&&(this.state.config.active_personality_id-=1);t("setMountedPersArr",e),this.state.mountedPers=this.state.personalities[this.state.personalities.findIndex(s=>s.full_path==this.state.config.personalities[this.state.config.active_personality_id]||s.full_path+":"+s.language==this.state.config.personalities[this.state.config.active_personality_id])]},async refreshBindings({commit:t}){let e=await Gs("list_bindings");console.log("Loaded bindings zoo :",e),this.state.installedBindings=e.filter(s=>s.installed),console.log("Loaded bindings zoo ",this.state.installedBindings),t("setbindingsZoo",e);const n=e.findIndex(s=>s.name==this.state.config.binding_name);n!=-1&&t("setCurrentBinding",e[n])},async refreshModelsZoo({commit:t}){console.log("Fetching models");const n=(await de.get("/get_available_models")).data.filter(s=>s.variants&&s.variants.length>0);console.log(`get_available_models: ${n}`),t("setModelsZoo",n)},async refreshModelStatus({commit:t}){let e=await Gs("get_model_status");t("setIsModelOk",e.status)},async refreshModels({commit:t}){console.log("Fetching models");let e=await Gs("list_models");console.log(`Found ${e}`);let n=await Gs("get_active_model");console.log("Selected model ",n),n!=null&&t("setselectedModel",n.model),t("setModelsArr",e),console.log("setModelsArr",e),console.log("this.state.modelsZoo",this.state.modelsZoo),this.state.modelsZoo.map(i=>{i.isInstalled=e.includes(i.name)}),this.state.installedModels=this.state.modelsZoo.filter(i=>i.isInstalled);const s=this.state.modelsZoo.findIndex(i=>i.name==this.state.config.model_name);s!=-1&&t("setCurrentModel",this.state.modelsZoo[s])},async refreshDiskUsage({commit:t}){this.state.diskUsage=await Gs("disk_usage")},async refreshRamUsage({commit:t}){this.state.ramUsage=await Gs("ram_usage")},async refreshVramUsage({commit:t}){const e=await Gs("vram_usage"),n=[];if(e.nb_gpus>0){for(let i=0;i LoLLMS WebUI - + diff --git a/web/src/views/AppsZoo.vue b/web/src/views/AppsZoo.vue index 308f327d..c9cf37eb 100644 --- a/web/src/views/AppsZoo.vue +++ b/web/src/views/AppsZoo.vue @@ -119,7 +119,7 @@ -