var __defProp=Object.defineProperty,__defProps=Object.defineProperties;var __getOwnPropDescs=Object.getOwnPropertyDescriptors;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable;var __typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__spreadValues=(a,b)=>{for(var prop in b||(b={}))__hasOwnProp.call(b,prop)&&__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b))__propIsEnum.call(b,prop)&&__defNormalProp(a,prop,b[prop]);return a},__spreadProps=(a,b)=>__defProps(a,__getOwnPropDescs(b)),__name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value),__accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg);var __privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);var __async=(__this,__arguments,generator)=>new Promise((resolve,reject)=>{var fulfilled=value=>{try{step(generator.next(value))}catch(e){reject(e)}},rejected=value=>{try{step(generator.throw(value))}catch(e){reject(e)}},step=x=>x.done?resolve(x.value):Promise.resolve(x.value).then(fulfilled,rejected);step((generator=generator.apply(__this,__arguments)).next())});import{C as ComfyDialog,$ as $el,a as ComfyApp,b as app,L as LGraphCanvas,c as LiteGraph,d as applyTextReplacements,e as ComfyWidgets,f as addValueControlWidgets,D as DraggableList,g as api,h as LGraphGroup,i as LGraphNode}from"./index-Dj_yIC5Q.js";const _ClipspaceDialog=class _ClipspaceDialog extends ComfyDialog{static registerButton(name,contextPredicate,callback){const item=$el("button",{type:"button",textContent:name,contextPredicate,onclick:callback});_ClipspaceDialog.items.push(item)}static invalidatePreview(){if(ComfyApp.clipspace&&ComfyApp.clipspace.imgs&&ComfyApp.clipspace.imgs.length>0){const img_preview=document.getElementById("clipspace_preview");img_preview&&(img_preview.src=ComfyApp.clipspace.imgs[ComfyApp.clipspace.selectedIndex].src,img_preview.style.maxHeight="100%",img_preview.style.maxWidth="100%")}}static invalidate(){if(_ClipspaceDialog.instance){const self=_ClipspaceDialog.instance,children=$el("div.comfy-modal-content",[self.createImgSettings(),...self.createButtons()]);self.element?(self.element.removeChild(self.element.firstChild),self.element.appendChild(children)):self.element=$el("div.comfy-modal",{parent:document.body},[children]),self.element.children[0].children.length<=1&&self.element.children[0].appendChild($el("p",{},["Unable to find the features to edit content of a format stored in the current Clipspace."])),_ClipspaceDialog.invalidatePreview()}}constructor(){super()}createButtons(){const buttons=[];for(let idx in _ClipspaceDialog.items){const item=_ClipspaceDialog.items[idx];(!item.contextPredicate||item.contextPredicate())&&buttons.push(_ClipspaceDialog.items[idx])}return buttons.push($el("button",{type:"button",textContent:"Close",onclick:__name(()=>{this.close()},"onclick")})),buttons}createImgSettings(){if(ComfyApp.clipspace.imgs){const combo_items=[],imgs=ComfyApp.clipspace.imgs;for(let i=0;i{ComfyApp.clipspace.selectedIndex=event.target.selectedIndex,_ClipspaceDialog.invalidatePreview()},"onchange")},combo_items),row1=$el("tr",{},[$el("td",{},[$el("font",{color:"white"},["Select Image"])]),$el("td",{},[combo1])]),combo2=$el("select",{id:"clipspace_img_paste_mode",onchange:__name(event=>{ComfyApp.clipspace.img_paste_mode=event.target.value},"onchange")},[$el("option",{value:"selected"},"selected"),$el("option",{value:"all"},"all")]);combo2.value=ComfyApp.clipspace.img_paste_mode;const row2=$el("tr",{},[$el("td",{},[$el("font",{color:"white"},["Paste Mode"])]),$el("td",{},[combo2])]),td=$el("td",{align:"center",width:"100px",height:"100px",colSpan:"2"},[$el("img",{id:"clipspace_preview",ondragstart:__name(()=>!1,"ondragstart")},[])]),row3=$el("tr",{},[td]);return $el("table",{},[row1,row2,row3])}else return[]}createImgPreview(){return ComfyApp.clipspace.imgs?$el("img",{id:"clipspace_preview",ondragstart:__name(()=>!1,"ondragstart")}):[]}show(){const img_preview=document.getElementById("clipspace_preview");_ClipspaceDialog.invalidate(),this.element.style.display="block"}};__name(_ClipspaceDialog,"ClipspaceDialog"),__publicField(_ClipspaceDialog,"items",[]),__publicField(_ClipspaceDialog,"instance",null);let ClipspaceDialog=_ClipspaceDialog;app.registerExtension({name:"Comfy.Clipspace",init(app2){app2.openClipspace=function(){ClipspaceDialog.instance||(ClipspaceDialog.instance=new ClipspaceDialog,ComfyApp.clipspace_invalidate_handler=ClipspaceDialog.invalidate),ComfyApp.clipspace?ClipspaceDialog.instance.show():app2.ui.dialog.show("Clipspace is Empty!")}}});window.comfyAPI=window.comfyAPI||{};window.comfyAPI.clipspace=window.comfyAPI.clipspace||{};window.comfyAPI.clipspace.ClipspaceDialog=ClipspaceDialog;const colorPalettes={dark:{id:"dark",name:"Dark (Default)",colors:{node_slot:{CLIP:"#FFD500",CLIP_VISION:"#A8DADC",CLIP_VISION_OUTPUT:"#ad7452",CONDITIONING:"#FFA931",CONTROL_NET:"#6EE7B7",IMAGE:"#64B5F6",LATENT:"#FF9CF9",MASK:"#81C784",MODEL:"#B39DDB",STYLE_MODEL:"#C2FFAE",VAE:"#FF6E6E",NOISE:"#B0B0B0",GUIDER:"#66FFFF",SAMPLER:"#ECB4B4",SIGMAS:"#CDFFCD",TAESD:"#DCC274"},litegraph_base:{BACKGROUND_IMAGE:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=",CLEAR_BACKGROUND_COLOR:"#222",NODE_TITLE_COLOR:"#999",NODE_SELECTED_TITLE_COLOR:"#FFF",NODE_TEXT_SIZE:14,NODE_TEXT_COLOR:"#AAA",NODE_SUBTEXT_SIZE:12,NODE_DEFAULT_COLOR:"#333",NODE_DEFAULT_BGCOLOR:"#353535",NODE_DEFAULT_BOXCOLOR:"#666",NODE_DEFAULT_SHAPE:"box",NODE_BOX_OUTLINE_COLOR:"#FFF",DEFAULT_SHADOW_COLOR:"rgba(0,0,0,0.5)",DEFAULT_GROUP_FONT:24,WIDGET_BGCOLOR:"#222",WIDGET_OUTLINE_COLOR:"#666",WIDGET_TEXT_COLOR:"#DDD",WIDGET_SECONDARY_TEXT_COLOR:"#999",LINK_COLOR:"#9A9",EVENT_LINK_COLOR:"#A86",CONNECTING_LINK_COLOR:"#AFA"},comfy_base:{"fg-color":"#fff","bg-color":"#202020","comfy-menu-bg":"#353535","comfy-input-bg":"#222","input-text":"#ddd","descrip-text":"#999","drag-text":"#ccc","error-text":"#ff4444","border-color":"#4e4e4e","tr-even-bg-color":"#222","tr-odd-bg-color":"#353535","content-bg":"#4e4e4e","content-fg":"#fff","content-hover-bg":"#222","content-hover-fg":"#fff"}}},light:{id:"light",name:"Light",colors:{node_slot:{CLIP:"#FFA726",CLIP_VISION:"#5C6BC0",CLIP_VISION_OUTPUT:"#8D6E63",CONDITIONING:"#EF5350",CONTROL_NET:"#66BB6A",IMAGE:"#42A5F5",LATENT:"#AB47BC",MASK:"#9CCC65",MODEL:"#7E57C2",STYLE_MODEL:"#D4E157",VAE:"#FF7043"},litegraph_base:{BACKGROUND_IMAGE:"data:image/gif;base64,R0lGODlhZABkALMAAAAAAP///+vr6+rq6ujo6Ofn5+bm5uXl5d3d3f///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAABkAGQAAAT/UMhJq7046827HkcoHkYxjgZhnGG6si5LqnIM0/fL4qwwIMAg0CAsEovBIxKhRDaNy2GUOX0KfVFrssrNdpdaqTeKBX+dZ+jYvEaTf+y4W66mC8PUdrE879f9d2mBeoNLfH+IhYBbhIx2jkiHiomQlGKPl4uZe3CaeZifnnijgkESBqipqqusra6vsLGys62SlZO4t7qbuby7CLa+wqGWxL3Gv3jByMOkjc2lw8vOoNSi0czAncXW3Njdx9Pf48/Z4Kbbx+fQ5evZ4u3k1fKR6cn03vHlp7T9/v8A/8Gbp4+gwXoFryXMB2qgwoMMHyKEqA5fxX322FG8tzBcRnMW/zlulPbRncmQGidKjMjyYsOSKEF2FBlJQMCbOHP6c9iSZs+UnGYCdbnSo1CZI5F64kn0p1KnTH02nSoV3dGTV7FFHVqVq1dtWcMmVQZTbNGu72zqXMuW7danVL+6e4t1bEy6MeueBYLXrNO5Ze36jQtWsOG97wIj1vt3St/DjTEORss4nNq2mDP3e7w4r1bFkSET5hy6s2TRlD2/mSxXtSHQhCunXo26NevCpmvD/UU6tuullzULH76q92zdZG/Ltv1a+W+osI/nRmyc+fRi1Xdbh+68+0vv10dH3+77KD/i6IdnX669/frn5Zsjh4/2PXju8+8bzc9/6fj27LFnX11/+IUnXWl7BJfegm79FyB9JOl3oHgSklefgxAC+FmFGpqHIYcCfkhgfCohSKKJVo044YUMttggiBkmp6KFXw1oII24oYhjiDByaKOOHcp3Y5BD/njikSkO+eBREQAAOw==",CLEAR_BACKGROUND_COLOR:"lightgray",NODE_TITLE_COLOR:"#222",NODE_SELECTED_TITLE_COLOR:"#000",NODE_TEXT_SIZE:14,NODE_TEXT_COLOR:"#444",NODE_SUBTEXT_SIZE:12,NODE_DEFAULT_COLOR:"#F7F7F7",NODE_DEFAULT_BGCOLOR:"#F5F5F5",NODE_DEFAULT_BOXCOLOR:"#CCC",NODE_DEFAULT_SHAPE:"box",NODE_BOX_OUTLINE_COLOR:"#000",DEFAULT_SHADOW_COLOR:"rgba(0,0,0,0.1)",DEFAULT_GROUP_FONT:24,WIDGET_BGCOLOR:"#D4D4D4",WIDGET_OUTLINE_COLOR:"#999",WIDGET_TEXT_COLOR:"#222",WIDGET_SECONDARY_TEXT_COLOR:"#555",LINK_COLOR:"#4CAF50",EVENT_LINK_COLOR:"#FF9800",CONNECTING_LINK_COLOR:"#2196F3"},comfy_base:{"fg-color":"#222","bg-color":"#DDD","comfy-menu-bg":"#F5F5F5","comfy-input-bg":"#C9C9C9","input-text":"#222","descrip-text":"#444","drag-text":"#555","error-text":"#F44336","border-color":"#888","tr-even-bg-color":"#f9f9f9","tr-odd-bg-color":"#fff","content-bg":"#e0e0e0","content-fg":"#222","content-hover-bg":"#adadad","content-hover-fg":"#222"}}},solarized:{id:"solarized",name:"Solarized",colors:{node_slot:{CLIP:"#2AB7CA",CLIP_VISION:"#6c71c4",CLIP_VISION_OUTPUT:"#859900",CONDITIONING:"#d33682",CONTROL_NET:"#d1ffd7",IMAGE:"#5940bb",LATENT:"#268bd2",MASK:"#CCC9E7",MODEL:"#dc322f",STYLE_MODEL:"#1a998a",UPSCALE_MODEL:"#054A29",VAE:"#facfad"},litegraph_base:{NODE_TITLE_COLOR:"#fdf6e3",NODE_SELECTED_TITLE_COLOR:"#A9D400",NODE_TEXT_SIZE:14,NODE_TEXT_COLOR:"#657b83",NODE_SUBTEXT_SIZE:12,NODE_DEFAULT_COLOR:"#094656",NODE_DEFAULT_BGCOLOR:"#073642",NODE_DEFAULT_BOXCOLOR:"#839496",NODE_DEFAULT_SHAPE:"box",NODE_BOX_OUTLINE_COLOR:"#fdf6e3",DEFAULT_SHADOW_COLOR:"rgba(0,0,0,0.5)",DEFAULT_GROUP_FONT:24,WIDGET_BGCOLOR:"#002b36",WIDGET_OUTLINE_COLOR:"#839496",WIDGET_TEXT_COLOR:"#fdf6e3",WIDGET_SECONDARY_TEXT_COLOR:"#93a1a1",LINK_COLOR:"#2aa198",EVENT_LINK_COLOR:"#268bd2",CONNECTING_LINK_COLOR:"#859900"},comfy_base:{"fg-color":"#fdf6e3","bg-color":"#002b36","comfy-menu-bg":"#073642","comfy-input-bg":"#002b36","input-text":"#93a1a1","descrip-text":"#586e75","drag-text":"#839496","error-text":"#dc322f","border-color":"#657b83","tr-even-bg-color":"#002b36","tr-odd-bg-color":"#073642","content-bg":"#657b83","content-fg":"#fdf6e3","content-hover-bg":"#002b36","content-hover-fg":"#fdf6e3"}}},arc:{id:"arc",name:"Arc",colors:{node_slot:{BOOLEAN:"",CLIP:"#eacb8b",CLIP_VISION:"#A8DADC",CLIP_VISION_OUTPUT:"#ad7452",CONDITIONING:"#cf876f",CONTROL_NET:"#00d78d",CONTROL_NET_WEIGHTS:"",FLOAT:"",GLIGEN:"",IMAGE:"#80a1c0",IMAGEUPLOAD:"",INT:"",LATENT:"#b38ead",LATENT_KEYFRAME:"",MASK:"#a3bd8d",MODEL:"#8978a7",SAMPLER:"",SIGMAS:"",STRING:"",STYLE_MODEL:"#C2FFAE",T2I_ADAPTER_WEIGHTS:"",TAESD:"#DCC274",TIMESTEP_KEYFRAME:"",UPSCALE_MODEL:"",VAE:"#be616b"},litegraph_base:{BACKGROUND_IMAGE:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAACXBIWXMAAAsTAAALEwEAmpwYAAABcklEQVR4nO3YMUoDARgF4RfxBqZI6/0vZqFn0MYtrLIQMFN8U6V4LAtD+Jm9XG/v30OGl2e/AP7yevz4+vx45nvgF/+QGITEICQGITEIiUFIjNNC3q43u3/YnRJyPOzeQ+0e220nhRzReC8e7R7bbdvl+Jal1Bs46jEIiUFIDEJiEBKDkBhKPbZT6qHdptRTu02p53DUYxASg5AYhMQgJAYhMZR6bKfUQ7tNqad2m1LP4ajHICQGITEIiUFIDEJiKPXYTqmHdptST+02pZ7DUY9BSAxCYhASg5AYhMRQ6rGdUg/tNqWe2m1KPYejHoOQGITEICQGITEIiaHUYzulHtptSj2125R6Dkc9BiExCIlBSAxCYhASQ6nHdko9tNuUemq3KfUcjnoMQmIQEoOQGITEICSGUo/tlHpotyn11G5T6jkc9RiExCAkBiExCIlBSAylHtsp9dBuU+qp3abUczjqMQiJQUgMQmIQEoOQGITE+AHFISNQrFTGuwAAAABJRU5ErkJggg==",CLEAR_BACKGROUND_COLOR:"#2b2f38",NODE_TITLE_COLOR:"#b2b7bd",NODE_SELECTED_TITLE_COLOR:"#FFF",NODE_TEXT_SIZE:14,NODE_TEXT_COLOR:"#AAA",NODE_SUBTEXT_SIZE:12,NODE_DEFAULT_COLOR:"#2b2f38",NODE_DEFAULT_BGCOLOR:"#242730",NODE_DEFAULT_BOXCOLOR:"#6e7581",NODE_DEFAULT_SHAPE:"box",NODE_BOX_OUTLINE_COLOR:"#FFF",DEFAULT_SHADOW_COLOR:"rgba(0,0,0,0.5)",DEFAULT_GROUP_FONT:22,WIDGET_BGCOLOR:"#2b2f38",WIDGET_OUTLINE_COLOR:"#6e7581",WIDGET_TEXT_COLOR:"#DDD",WIDGET_SECONDARY_TEXT_COLOR:"#b2b7bd",LINK_COLOR:"#9A9",EVENT_LINK_COLOR:"#A86",CONNECTING_LINK_COLOR:"#AFA"},comfy_base:{"fg-color":"#fff","bg-color":"#2b2f38","comfy-menu-bg":"#242730","comfy-input-bg":"#2b2f38","input-text":"#ddd","descrip-text":"#b2b7bd","drag-text":"#ccc","error-text":"#ff4444","border-color":"#6e7581","tr-even-bg-color":"#2b2f38","tr-odd-bg-color":"#242730","content-bg":"#6e7581","content-fg":"#fff","content-hover-bg":"#2b2f38","content-hover-fg":"#fff"}}},nord:{id:"nord",name:"Nord",colors:{node_slot:{BOOLEAN:"",CLIP:"#eacb8b",CLIP_VISION:"#A8DADC",CLIP_VISION_OUTPUT:"#ad7452",CONDITIONING:"#cf876f",CONTROL_NET:"#00d78d",CONTROL_NET_WEIGHTS:"",FLOAT:"",GLIGEN:"",IMAGE:"#80a1c0",IMAGEUPLOAD:"",INT:"",LATENT:"#b38ead",LATENT_KEYFRAME:"",MASK:"#a3bd8d",MODEL:"#8978a7",SAMPLER:"",SIGMAS:"",STRING:"",STYLE_MODEL:"#C2FFAE",T2I_ADAPTER_WEIGHTS:"",TAESD:"#DCC274",TIMESTEP_KEYFRAME:"",UPSCALE_MODEL:"",VAE:"#be616b"},litegraph_base:{BACKGROUND_IMAGE:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFu2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDEgNzkuMTQ2Mjg5OSwgMjAyMy8wNi8yNS0yMDowMTo1NSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiB4bXA6Q3JlYXRlRGF0ZT0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgeG1wOk1vZGlmeURhdGU9IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIHhtcDpNZXRhZGF0YURhdGU9IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIiBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjUwNDFhMmZjLTEzNzQtMTk0ZC1hZWY4LTYxMzM1MTVmNjUwMCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyMzFiMTBiMC1iNGZiLTAyNGUtYjEyZS0zMDUzMDNjZDA3YzgiIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDoyMzFiMTBiMC1iNGZiLTAyNGUtYjEyZS0zMDUzMDNjZDA3YzgiPiA8eG1wTU06SGlzdG9yeT4gPHJkZjpTZXE+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJjcmVhdGVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjIzMWIxMGIwLWI0ZmItMDI0ZS1iMTJlLTMwNTMwM2NkMDdjOCIgc3RFdnQ6d2hlbj0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJzYXZlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo1MDQxYTJmYy0xMzc0LTE5NGQtYWVmOC02MTMzNTE1ZjY1MDAiIHN0RXZ0OndoZW49IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNS4xIChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz73jWg/AAAAyUlEQVR42u3WKwoAIBRFQRdiMb1idv9Lsxn9gEFw4Dbb8JCTojbbXEJwjJVL2HKwYMGCBQuWLbDmjr+9zrBGjHl1WVcvy2DBggULFizTWQpewSt4HzwsgwULFiwFr7MUvMtS8D54WLBgGSxYCl7BK3iXZbBgwYIFC5bpLAWv4BW8Dx6WwYIFC5aC11kK3mUpeB88LFiwDBYsBa/gFbzLMliwYMGCBct0loJX8AreBw/LYMGCBUvB6ywF77IUvA8eFixYBgsWrNfWAZPltufdad+1AAAAAElFTkSuQmCC",CLEAR_BACKGROUND_COLOR:"#212732",NODE_TITLE_COLOR:"#999",NODE_SELECTED_TITLE_COLOR:"#e5eaf0",NODE_TEXT_SIZE:14,NODE_TEXT_COLOR:"#bcc2c8",NODE_SUBTEXT_SIZE:12,NODE_DEFAULT_COLOR:"#2e3440",NODE_DEFAULT_BGCOLOR:"#161b22",NODE_DEFAULT_BOXCOLOR:"#545d70",NODE_DEFAULT_SHAPE:"box",NODE_BOX_OUTLINE_COLOR:"#e5eaf0",DEFAULT_SHADOW_COLOR:"rgba(0,0,0,0.5)",DEFAULT_GROUP_FONT:24,WIDGET_BGCOLOR:"#2e3440",WIDGET_OUTLINE_COLOR:"#545d70",WIDGET_TEXT_COLOR:"#bcc2c8",WIDGET_SECONDARY_TEXT_COLOR:"#999",LINK_COLOR:"#9A9",EVENT_LINK_COLOR:"#A86",CONNECTING_LINK_COLOR:"#AFA"},comfy_base:{"fg-color":"#e5eaf0","bg-color":"#2e3440","comfy-menu-bg":"#161b22","comfy-input-bg":"#2e3440","input-text":"#bcc2c8","descrip-text":"#999","drag-text":"#ccc","error-text":"#ff4444","border-color":"#545d70","tr-even-bg-color":"#2e3440","tr-odd-bg-color":"#161b22","content-bg":"#545d70","content-fg":"#e5eaf0","content-hover-bg":"#2e3440","content-hover-fg":"#e5eaf0"}}},github:{id:"github",name:"Github",colors:{node_slot:{BOOLEAN:"",CLIP:"#eacb8b",CLIP_VISION:"#A8DADC",CLIP_VISION_OUTPUT:"#ad7452",CONDITIONING:"#cf876f",CONTROL_NET:"#00d78d",CONTROL_NET_WEIGHTS:"",FLOAT:"",GLIGEN:"",IMAGE:"#80a1c0",IMAGEUPLOAD:"",INT:"",LATENT:"#b38ead",LATENT_KEYFRAME:"",MASK:"#a3bd8d",MODEL:"#8978a7",SAMPLER:"",SIGMAS:"",STRING:"",STYLE_MODEL:"#C2FFAE",T2I_ADAPTER_WEIGHTS:"",TAESD:"#DCC274",TIMESTEP_KEYFRAME:"",UPSCALE_MODEL:"",VAE:"#be616b"},litegraph_base:{BACKGROUND_IMAGE:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAGlmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDEgNzkuMTQ2Mjg5OSwgMjAyMy8wNi8yNS0yMDowMTo1NSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiB4bXA6Q3JlYXRlRGF0ZT0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgeG1wOk1vZGlmeURhdGU9IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIHhtcDpNZXRhZGF0YURhdGU9IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIiBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOmIyYzRhNjA5LWJmYTctYTg0MC1iOGFlLTk3MzE2ZjM1ZGIyNyIgeG1wTU06RG9jdW1lbnRJRD0iYWRvYmU6ZG9jaWQ6cGhvdG9zaG9wOjk0ZmNlZGU4LTE1MTctZmQ0MC04ZGU3LWYzOTgxM2E3ODk5ZiIgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOjIzMWIxMGIwLWI0ZmItMDI0ZS1iMTJlLTMwNTMwM2NkMDdjOCI+IDx4bXBNTTpIaXN0b3J5PiA8cmRmOlNlcT4gPHJkZjpsaSBzdEV2dDphY3Rpb249ImNyZWF0ZWQiIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6MjMxYjEwYjAtYjRmYi0wMjRlLWIxMmUtMzA1MzAzY2QwN2M4IiBzdEV2dDp3aGVuPSIyMDIzLTExLTEzVDAwOjE4OjAyKzAxOjAwIiBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgMjUuMSAoV2luZG93cykiLz4gPHJkZjpsaSBzdEV2dDphY3Rpb249InNhdmVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjQ4OWY1NzlmLTJkNjUtZWQ0Zi04OTg0LTA4NGE2MGE1ZTMzNSIgc3RFdnQ6d2hlbj0iMjAyMy0xMS0xNVQwMjowNDo1OSswMTowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiBzdEV2dDpjaGFuZ2VkPSIvIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJzYXZlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDpiMmM0YTYwOS1iZmE3LWE4NDAtYjhhZS05NzMxNmYzNWRiMjciIHN0RXZ0OndoZW49IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNS4xIChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4OTe6GAAAAx0lEQVR42u3WMQoAIQxFwRzJys77X8vSLiRgITif7bYbgrwYc/mKXyBoY4VVBgsWLFiwYFmOlTv+9jfDOjHmr8u6eVkGCxYsWLBgmc5S8ApewXvgYRksWLBgKXidpeBdloL3wMOCBctgwVLwCl7BuyyDBQsWLFiwTGcpeAWv4D3wsAwWLFiwFLzOUvAuS8F74GHBgmWwYCl4Ba/gXZbBggULFixYprMUvIJX8B54WAYLFixYCl5nKXiXpeA98LBgwTJYsGC9tg1o8f4TTtqzNQAAAABJRU5ErkJggg==",CLEAR_BACKGROUND_COLOR:"#040506",NODE_TITLE_COLOR:"#999",NODE_SELECTED_TITLE_COLOR:"#e5eaf0",NODE_TEXT_SIZE:14,NODE_TEXT_COLOR:"#bcc2c8",NODE_SUBTEXT_SIZE:12,NODE_DEFAULT_COLOR:"#161b22",NODE_DEFAULT_BGCOLOR:"#13171d",NODE_DEFAULT_BOXCOLOR:"#30363d",NODE_DEFAULT_SHAPE:"box",NODE_BOX_OUTLINE_COLOR:"#e5eaf0",DEFAULT_SHADOW_COLOR:"rgba(0,0,0,0.5)",DEFAULT_GROUP_FONT:24,WIDGET_BGCOLOR:"#161b22",WIDGET_OUTLINE_COLOR:"#30363d",WIDGET_TEXT_COLOR:"#bcc2c8",WIDGET_SECONDARY_TEXT_COLOR:"#999",LINK_COLOR:"#9A9",EVENT_LINK_COLOR:"#A86",CONNECTING_LINK_COLOR:"#AFA"},comfy_base:{"fg-color":"#e5eaf0","bg-color":"#161b22","comfy-menu-bg":"#13171d","comfy-input-bg":"#161b22","input-text":"#bcc2c8","descrip-text":"#999","drag-text":"#ccc","error-text":"#ff4444","border-color":"#30363d","tr-even-bg-color":"#161b22","tr-odd-bg-color":"#13171d","content-bg":"#30363d","content-fg":"#e5eaf0","content-hover-bg":"#161b22","content-hover-fg":"#e5eaf0"}}}},id$4="Comfy.ColorPalette",idCustomColorPalettes="Comfy.CustomColorPalettes",defaultColorPaletteId="dark",els={select:null};app.registerExtension({name:id$4,init(){LGraphCanvas.prototype.updateBackground=function(image,clearBackgroundColor){this._bg_img=new Image,this._bg_img.name=image,this._bg_img.src=image,this._bg_img.onload=()=>{this.draw(!0,!0)},this.background_image=image,this.clear_background=!0,this.clear_background_color=clearBackgroundColor,this._pattern=null}},addCustomNodeDefs(node_defs){const sortObjectKeys=__name(unordered=>Object.keys(unordered).sort().reduce((obj,key)=>(obj[key]=unordered[key],obj),{}),"sortObjectKeys");function getSlotTypes(){var types=[];const defs=node_defs;for(const nodeId in defs){const nodeData=defs[nodeId];var inputs=nodeData.input.required;nodeData.input.optional!==void 0&&(inputs=Object.assign({},nodeData.input.required,nodeData.input.optional));for(const inputName in inputs){const type=inputs[inputName][0];Array.isArray(type)||types.push(type)}for(const o in nodeData.output){const output=nodeData.output[o];types.push(output)}}return types}__name(getSlotTypes,"getSlotTypes");function completeColorPalette(colorPalette){var types=getSlotTypes();for(const type of types)colorPalette.colors.node_slot[type]||(colorPalette.colors.node_slot[type]="");return colorPalette.colors.node_slot=sortObjectKeys(colorPalette.colors.node_slot),colorPalette}__name(completeColorPalette,"completeColorPalette");const getColorPaletteTemplate=__name(()=>__async(this,null,function*(){let colorPalette={id:"my_color_palette_unique_id",name:"My Color Palette",colors:{node_slot:{},litegraph_base:{},comfy_base:{}}};const defaultColorPalette=colorPalettes[defaultColorPaletteId];for(const key in defaultColorPalette.colors.litegraph_base)colorPalette.colors.litegraph_base[key]||(colorPalette.colors.litegraph_base[key]="");for(const key in defaultColorPalette.colors.comfy_base)colorPalette.colors.comfy_base[key]||(colorPalette.colors.comfy_base[key]="");return completeColorPalette(colorPalette)}),"getColorPaletteTemplate"),getCustomColorPalettes=__name(()=>app.ui.settings.getSettingValue(idCustomColorPalettes,{}),"getCustomColorPalettes"),setCustomColorPalettes=__name(customColorPalettes=>app.ui.settings.setSettingValue(idCustomColorPalettes,customColorPalettes),"setCustomColorPalettes"),addCustomColorPalette=__name(colorPalette=>__async(this,null,function*(){if(typeof colorPalette!="object"){alert("Invalid color palette.");return}if(!colorPalette.id){alert("Color palette missing id.");return}if(!colorPalette.name){alert("Color palette missing name.");return}if(!colorPalette.colors){alert("Color palette missing colors.");return}if(colorPalette.colors.node_slot&&typeof colorPalette.colors.node_slot!="object"){alert("Invalid color palette colors.node_slot.");return}const customColorPalettes=getCustomColorPalettes();customColorPalettes[colorPalette.id]=colorPalette,setCustomColorPalettes(customColorPalettes);for(const option of els.select.childNodes)option.value==="custom_"+colorPalette.id&&els.select.removeChild(option);els.select.append($el("option",{textContent:colorPalette.name+" (custom)",value:"custom_"+colorPalette.id,selected:!0})),setColorPalette("custom_"+colorPalette.id),yield loadColorPalette(colorPalette)}),"addCustomColorPalette"),deleteCustomColorPalette=__name(colorPaletteId=>__async(this,null,function*(){const customColorPalettes=getCustomColorPalettes();delete customColorPalettes[colorPaletteId],setCustomColorPalettes(customColorPalettes);for(const opt of els.select.childNodes){const option=opt;option.value===defaultColorPaletteId&&(option.selected=!0),option.value==="custom_"+colorPaletteId&&els.select.removeChild(option)}setColorPalette(defaultColorPaletteId),yield loadColorPalette(getColorPalette())}),"deleteCustomColorPalette"),loadColorPalette=__name(colorPalette=>__async(this,null,function*(){if(colorPalette=yield completeColorPalette(colorPalette),colorPalette.colors){if(colorPalette.colors.node_slot&&(Object.assign(app.canvas.default_connection_color_byType,colorPalette.colors.node_slot),Object.assign(LGraphCanvas.link_type_colors,colorPalette.colors.node_slot)),colorPalette.colors.litegraph_base){app.canvas.node_title_color=colorPalette.colors.litegraph_base.NODE_TITLE_COLOR,app.canvas.default_link_color=colorPalette.colors.litegraph_base.LINK_COLOR;for(const key in colorPalette.colors.litegraph_base)colorPalette.colors.litegraph_base.hasOwnProperty(key)&&LiteGraph.hasOwnProperty(key)&&(LiteGraph[key]=colorPalette.colors.litegraph_base[key])}if(colorPalette.colors.comfy_base){const rootStyle=document.documentElement.style;for(const key in colorPalette.colors.comfy_base)rootStyle.setProperty("--"+key,colorPalette.colors.comfy_base[key])}app.canvas.draw(!0,!0)}}),"loadColorPalette"),getColorPalette=__name(colorPaletteId=>{if(colorPaletteId||(colorPaletteId=app.ui.settings.getSettingValue(id$4,defaultColorPaletteId)),colorPaletteId.startsWith("custom_")){colorPaletteId=colorPaletteId.substr(7);let customColorPalettes=getCustomColorPalettes();if(customColorPalettes[colorPaletteId])return customColorPalettes[colorPaletteId]}return colorPalettes[colorPaletteId]},"getColorPalette"),setColorPalette=__name(colorPaletteId=>{app.ui.settings.setSettingValue(id$4,colorPaletteId)},"setColorPalette"),fileInput=$el("input",{type:"file",accept:".json",style:{display:"none"},parent:document.body,onchange:__name(()=>{const file2=fileInput.files[0];if(file2.type==="application/json"||file2.name.endsWith(".json")){const reader=new FileReader;reader.onload=()=>__async(this,null,function*(){yield addCustomColorPalette(JSON.parse(reader.result))}),reader.readAsText(file2)}},"onchange")});app.ui.settings.addSetting({id:id$4,name:"Color Palette",type:__name((name,setter,value)=>{const options=[...Object.values(colorPalettes).map(c=>$el("option",{textContent:c.name,value:c.id,selected:c.id===value})),...Object.values(getCustomColorPalettes()).map(c=>$el("option",{textContent:`${c.name} (custom)`,value:`custom_${c.id}`,selected:`custom_${c.id}`===value}))];return els.select=$el("select",{style:{marginBottom:"0.15rem",width:"100%"},onchange:__name(e=>{setter(e.target.value)},"onchange")},options),$el("tr",[$el("td",[$el("label",{for:id$4.replaceAll(".","-"),textContent:"Color palette"})]),$el("td",[els.select,$el("div",{style:{display:"grid",gap:"4px",gridAutoFlow:"column"}},[$el("input",{type:"button",value:"Export",onclick:__name(()=>__async(this,null,function*(){const colorPaletteId=app.ui.settings.getSettingValue(id$4,defaultColorPaletteId),colorPalette=yield completeColorPalette(getColorPalette(colorPaletteId)),json=JSON.stringify(colorPalette,null,2),blob=new Blob([json],{type:"application/json"}),url=URL.createObjectURL(blob),a=$el("a",{href:url,download:colorPaletteId+".json",style:{display:"none"},parent:document.body});a.click(),setTimeout(function(){a.remove(),window.URL.revokeObjectURL(url)},0)}),"onclick")}),$el("input",{type:"button",value:"Import",onclick:__name(()=>{fileInput.click()},"onclick")}),$el("input",{type:"button",value:"Template",onclick:__name(()=>__async(this,null,function*(){const colorPalette=yield getColorPaletteTemplate(),json=JSON.stringify(colorPalette,null,2),blob=new Blob([json],{type:"application/json"}),url=URL.createObjectURL(blob),a=$el("a",{href:url,download:"color_palette.json",style:{display:"none"},parent:document.body});a.click(),setTimeout(function(){a.remove(),window.URL.revokeObjectURL(url)},0)}),"onclick")}),$el("input",{type:"button",value:"Delete",onclick:__name(()=>__async(this,null,function*(){let colorPaletteId=app.ui.settings.getSettingValue(id$4,defaultColorPaletteId);if(colorPalettes[colorPaletteId]){alert("You cannot delete a built-in color palette.");return}colorPaletteId.startsWith("custom_")&&(colorPaletteId=colorPaletteId.substr(7)),yield deleteCustomColorPalette(colorPaletteId)}),"onclick")})])])])},"type"),defaultValue:defaultColorPaletteId,onChange(value){return __async(this,null,function*(){if(!value)return;let palette=colorPalettes[value];if(palette)yield loadColorPalette(palette);else if(value.startsWith("custom_")){value=value.substr(7);let customColorPalettes=getCustomColorPalettes();customColorPalettes[value]&&(palette=customColorPalettes[value],yield loadColorPalette(customColorPalettes[value]))}let{BACKGROUND_IMAGE,CLEAR_BACKGROUND_COLOR}=palette.colors.litegraph_base;if(BACKGROUND_IMAGE===void 0||CLEAR_BACKGROUND_COLOR===void 0){const base=colorPalettes.dark.colors.litegraph_base;BACKGROUND_IMAGE=base.BACKGROUND_IMAGE,CLEAR_BACKGROUND_COLOR=base.CLEAR_BACKGROUND_COLOR}app.canvas.updateBackground(BACKGROUND_IMAGE,CLEAR_BACKGROUND_COLOR)})}})}});const ext$2={name:"Comfy.ContextMenuFilter",init(){const ctxMenu=LiteGraph.ContextMenu;LiteGraph.ContextMenu=function(values,options){const ctx=ctxMenu.call(this,values,options);if((options==null?void 0:options.className)==="dark"&&(values==null?void 0:values.length)>10){const filter=document.createElement("input");filter.classList.add("comfy-context-menu-filter"),filter.placeholder="Filter list",this.root.prepend(filter);const items=Array.from(this.root.querySelectorAll(".litemenu-entry"));let displayedItems=[...items],itemCount=displayedItems.length;requestAnimationFrame(()=>{var _a,_b;const clickedComboValue=(_b=(_a=LGraphCanvas.active_canvas.current_node.widgets)==null?void 0:_a.filter(w=>w.type==="combo"&&w.options.values.length===values.length).find(w=>w.options.values.every((v,i)=>v===values[i])))==null?void 0:_b.value;let selectedIndex=clickedComboValue?values.findIndex(v=>v===clickedComboValue):0;selectedIndex<0&&(selectedIndex=0);let selectedItem=displayedItems[selectedIndex];updateSelected();function updateSelected(){selectedItem==null||selectedItem.style.setProperty("background-color",""),selectedItem==null||selectedItem.style.setProperty("color",""),selectedItem=displayedItems[selectedIndex],selectedItem==null||selectedItem.style.setProperty("background-color","#ccc","important"),selectedItem==null||selectedItem.style.setProperty("color","#000","important")}__name(updateSelected,"updateSelected");const positionList=__name(()=>{if(this.root.getBoundingClientRect().top<0){const scale=1-this.root.getBoundingClientRect().height/this.root.clientHeight,shift=this.root.clientHeight*scale/2;this.root.style.top=-shift+"px"}},"positionList");filter.addEventListener("keydown",event=>{switch(event.key){case"ArrowUp":event.preventDefault(),selectedIndex===0?selectedIndex=itemCount-1:selectedIndex--,updateSelected();break;case"ArrowRight":event.preventDefault(),selectedIndex=itemCount-1,updateSelected();break;case"ArrowDown":event.preventDefault(),selectedIndex===itemCount-1?selectedIndex=0:selectedIndex++,updateSelected();break;case"ArrowLeft":event.preventDefault(),selectedIndex=0,updateSelected();break;case"Enter":selectedItem==null||selectedItem.click();break;case"Escape":this.close();break}}),filter.addEventListener("input",()=>{const term=filter.value.toLocaleLowerCase();if(displayedItems=items.filter(item=>{const isVisible=!term||item.textContent.toLocaleLowerCase().includes(term);return item.style.display=isVisible?"block":"none",isVisible}),selectedIndex=0,displayedItems.includes(selectedItem)&&(selectedIndex=displayedItems.findIndex(d=>d===selectedItem)),itemCount=displayedItems.length,updateSelected(),options.event){let top=options.event.clientY-10;const bodyRect=document.body.getBoundingClientRect(),rootRect=this.root.getBoundingClientRect();bodyRect.height&&top>bodyRect.height-rootRect.height-10&&(top=Math.max(0,bodyRect.height-rootRect.height-10)),this.root.style.top=top+"px",positionList()}}),requestAnimationFrame(()=>{filter.focus(),positionList()})})}return ctx},LiteGraph.ContextMenu.prototype=ctxMenu.prototype}};app.registerExtension(ext$2);function stripComments(str){return str.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,"")}__name(stripComments,"stripComments");app.registerExtension({name:"Comfy.DynamicPrompts",nodeCreated(node){if(node.widgets){const widgets=node.widgets.filter(n=>n.dynamicPrompts);for(const widget of widgets)widget.serializeValue=(workflowNode,widgetIndex)=>{let prompt2=stripComments(widget.value);for(;prompt2.replace("\\{","").includes("{")&&prompt2.replace("\\}","").includes("}");){const startIndex=prompt2.replace("\\{","00").indexOf("{"),endIndex=prompt2.replace("\\}","00").indexOf("}"),options=prompt2.substring(startIndex+1,endIndex).split("|"),randomIndex=Math.floor(Math.random()*options.length),randomOption=options[randomIndex];prompt2=prompt2.substring(0,startIndex)+randomOption+prompt2.substring(endIndex+1)}return workflowNode!=null&&workflowNode.widgets_values&&(workflowNode.widgets_values[widgetIndex]=prompt2),prompt2}}}});app.registerExtension({name:"Comfy.EditAttention",init(){const editAttentionDelta=app.ui.settings.addSetting({id:"Comfy.EditAttention.Delta",name:"Ctrl+up/down precision",type:"slider",attrs:{min:.01,max:.5,step:.01},defaultValue:.05});function incrementWeight(weight,delta){const floatWeight=parseFloat(weight);if(isNaN(floatWeight))return weight;const newWeight=floatWeight+delta;return newWeight<0?"0":String(Number(newWeight.toFixed(10)))}__name(incrementWeight,"incrementWeight");function findNearestEnclosure(text,cursorPos){let start=cursorPos,end=cursorPos,openCount=0,closeCount=0;for(;start>=0&&(start--,!(text[start]==="("&&openCount===closeCount));)text[start]==="("&&openCount++,text[start]===")"&&closeCount++;if(start<0)return!1;for(openCount=0,closeCount=0;end0;)start--;for(;!delimiters.includes(inputField.value[end])&&end(weight=incrementWeight(weight,weightDelta),weight==1?text:`(${text}:${weight})`));inputField.setRangeText(updatedText,start,end,"select")}__name(editAttention,"editAttention"),window.addEventListener("keydown",editAttention)}});const CONVERTED_TYPE="converted-widget",VALID_TYPES=["STRING","combo","number","toggle","BOOLEAN"],CONFIG=Symbol(),GET_CONFIG=Symbol(),TARGET=Symbol(),replacePropertyName="Run widget replace on values";var _PrimitiveNode_instances,onFirstConnection_fn,createWidget_fn,mergeWidgetConfig_fn,isValidConnection_fn,removeWidgets_fn;const _PrimitiveNode=class _PrimitiveNode{constructor(){__privateAdd(this,_PrimitiveNode_instances);__publicField(this,"controlValues");__publicField(this,"lastType");this.addOutput("connect to widget input","*"),this.serialize_widgets=!0,this.isVirtualNode=!0,(!this.properties||!(replacePropertyName in this.properties))&&this.addProperty(replacePropertyName,!1,"boolean")}applyToGraph(extraLinks=[]){var _a,_b;if(!((_a=this.outputs[0].links)!=null&&_a.length))return;function get_links(node){let links2=[];for(const l of node.outputs[0].links){const linkInfo=app.graph.links[l],n=node.graph.getNodeById(linkInfo.target_id);n.type=="Reroute"?links2=links2.concat(get_links(n)):links2.push(l)}return links2}__name(get_links,"get_links");let links=[...get_links(this).map(l=>app.graph.links[l]),...extraLinks],v=(_b=this.widgets)==null?void 0:_b[0].value;v&&this.properties[replacePropertyName]&&(v=applyTextReplacements(app,v));for(const linkInfo of links){const node=this.graph.getNodeById(linkInfo.target_id),input=node.inputs[linkInfo.target_slot];let widget;if(input.widget[TARGET])widget=input.widget[TARGET];else{const widgetName=input.widget.name;widgetName&&(widget=node.widgets.find(w=>w.name===widgetName))}widget&&(widget.value=v,widget.callback&&widget.callback(widget.value,app.canvas,node,app.canvas.graph_mouse,{}))}}refreshComboInNode(){var _a;const widget=(_a=this.widgets)==null?void 0:_a[0];(widget==null?void 0:widget.type)==="combo"&&(widget.options.values=this.outputs[0].widget[GET_CONFIG]()[0],widget.options.values.includes(widget.value)||(widget.value=widget.options.values[0],widget.callback(widget.value)))}onAfterGraphConfigured(){var _a,_b;if((_a=this.outputs[0].links)!=null&&_a.length&&!((_b=this.widgets)!=null&&_b.length)){if(!__privateMethod(this,_PrimitiveNode_instances,onFirstConnection_fn).call(this))return;if(this.widgets)for(let i=0;iw.value);if(__privateMethod(this,_PrimitiveNode_instances,removeWidgets_fn).call(this),__privateMethod(this,_PrimitiveNode_instances,onFirstConnection_fn).call(this,!0),values!=null&&values.length)for(let i=0;i<((_b=this.widgets)==null?void 0:_b.length);i++)this.widgets[i].value=values[i];return(_c=this.widgets)==null?void 0:_c[0]}onLastDisconnect(){this.outputs[0].type="*",this.outputs[0].name="connect to widget input",delete this.outputs[0].widget,__privateMethod(this,_PrimitiveNode_instances,removeWidgets_fn).call(this)}};_PrimitiveNode_instances=new WeakSet,onFirstConnection_fn=__name(function(recreating){var _a,_b;if(!this.outputs[0].links){this.onLastDisconnect();return}const linkId=this.outputs[0].links[0],link=this.graph.links[linkId];if(!link)return;const theirNode=this.graph.getNodeById(link.target_id);if(!theirNode||!theirNode.inputs)return;const input=theirNode.inputs[link.target_slot];if(!input)return;let widget;if(input.widget)widget=input.widget;else{if(!(input.type in ComfyWidgets))return;widget={name:input.name,[GET_CONFIG]:()=>[input.type,{}]}}const config=(_a=widget[GET_CONFIG])==null?void 0:_a.call(widget);if(!config)return;const{type}=getWidgetType(config);this.outputs[0].type=type,this.outputs[0].name=type,this.outputs[0].widget=widget,__privateMethod(this,_PrimitiveNode_instances,createWidget_fn).call(this,(_b=widget[CONFIG])!=null?_b:config,theirNode,widget.name,recreating,widget[TARGET])},"#onFirstConnection"),createWidget_fn=__name(function(inputData,node,widgetName,recreating,targetWidget){var _a,_b,_c;let type=inputData[0];type instanceof Array&&(type="COMBO");let widget;if(type in ComfyWidgets?widget=(ComfyWidgets[type](this,"value",inputData,app)||{}).widget:widget=this.addWidget(type,"value",null,()=>{},{}),targetWidget)widget.value=targetWidget.value;else if(node!=null&&node.widgets&&widget){const theirWidget=node.widgets.find(w=>w.name===widgetName);theirWidget&&(widget.value=theirWidget.value)}if(!((_a=inputData==null?void 0:inputData[1])!=null&&_a.control_after_generate)&&(widget.type==="number"||widget.type==="combo")){let control_value=(_b=this.widgets_values)==null?void 0:_b[1];control_value||(control_value="fixed"),addValueControlWidgets(this,widget,control_value,void 0,inputData);let filter=(_c=this.widgets_values)==null?void 0:_c[2];filter&&this.widgets.length===3&&(this.widgets[2].value=filter)}const controlValues=this.controlValues;if(this.lastType===this.widgets[0].type&&(controlValues==null?void 0:controlValues.length)===this.widgets.length-1)for(let i=0;i{this.onResize&&this.onResize(this.size)})}},"#createWidget"),mergeWidgetConfig_fn=__name(function(){const output=this.outputs[0],links=output.links,hasConfig=!!output.widget[CONFIG];if(hasConfig&&delete output.widget[CONFIG],(links==null?void 0:links.length)<2&&hasConfig){links.length&&this.recreateWidget();return}const config1=output.widget[GET_CONFIG]();if(config1[0]==="INT"||config1[0]==="FLOAT")for(const linkId of links){const link=app.graph.links[linkId];if(!link)continue;const theirInput=app.graph.getNodeById(link.target_id).inputs[link.target_slot];__privateMethod(this,_PrimitiveNode_instances,isValidConnection_fn).call(this,theirInput,hasConfig)}},"#mergeWidgetConfig"),isValidConnection_fn=__name(function(input,forceUpdate){const output=this.outputs[0],config2=input.widget[GET_CONFIG]();return!!mergeIfValid.call(this,output,config2,forceUpdate,this.recreateWidget)},"#isValidConnection"),removeWidgets_fn=__name(function(){var _a;if(this.widgets){for(const w of this.widgets)w.onRemove&&w.onRemove();this.controlValues=[],this.lastType=(_a=this.widgets[0])==null?void 0:_a.type;for(let i=1;i{delete this.lastType,delete this.controlValues},15),this.widgets.length=0}},"#removeWidgets"),__name(_PrimitiveNode,"PrimitiveNode"),__publicField(_PrimitiveNode,"category");let PrimitiveNode=_PrimitiveNode;function getWidgetConfig(slot){var _a;return(_a=slot.widget[CONFIG])!=null?_a:slot.widget[GET_CONFIG]()}__name(getWidgetConfig,"getWidgetConfig");function getConfig(widgetName){var _a,_b,_c,_d;const{nodeData}=this.constructor;return(_d=(_a=nodeData==null?void 0:nodeData.input)==null?void 0:_a.required[widgetName])!=null?_d:(_c=(_b=nodeData==null?void 0:nodeData.input)==null?void 0:_b.optional)==null?void 0:_c[widgetName]}__name(getConfig,"getConfig");function isConvertibleWidget(widget,config){var _a;return(VALID_TYPES.includes(widget.type)||VALID_TYPES.includes(config[0]))&&!((_a=widget.options)!=null&&_a.forceInput)}__name(isConvertibleWidget,"isConvertibleWidget");function hideWidget(node,widget,suffix=""){var _a;if(!((_a=widget.type)!=null&&_a.startsWith(CONVERTED_TYPE))&&(widget.origType=widget.type,widget.origComputeSize=widget.computeSize,widget.origSerializeValue=widget.serializeValue,widget.computeSize=()=>[0,-4],widget.type=CONVERTED_TYPE+suffix,widget.serializeValue=()=>{if(!node.inputs)return;let node_input=node.inputs.find(i=>{var _a2;return((_a2=i.widget)==null?void 0:_a2.name)===widget.name});if(!(!node_input||!node_input.link))return widget.origSerializeValue?widget.origSerializeValue():widget.value},widget.linkedWidgets))for(const w of widget.linkedWidgets)hideWidget(node,w,":"+widget.name)}__name(hideWidget,"hideWidget");function showWidget(widget){if(widget.type=widget.origType,widget.computeSize=widget.origComputeSize,widget.serializeValue=widget.origSerializeValue,delete widget.origType,delete widget.origComputeSize,delete widget.origSerializeValue,widget.linkedWidgets)for(const w of widget.linkedWidgets)showWidget(w)}__name(showWidget,"showWidget");function convertToInput(node,widget,config){hideWidget(node,widget);const{type}=getWidgetType(config),sz=node.size;node.addInput(widget.name,type,{widget:{name:widget.name,[GET_CONFIG]:()=>config}});for(const widget2 of node.widgets)widget2.last_y+=LiteGraph.NODE_SLOT_HEIGHT;node.setSize([Math.max(sz[0],node.size[0]),Math.max(sz[1],node.size[1])])}__name(convertToInput,"convertToInput");function convertToWidget(node,widget){showWidget(widget);const sz=node.size;node.removeInput(node.inputs.findIndex(i=>{var _a;return((_a=i.widget)==null?void 0:_a.name)===widget.name}));for(const widget2 of node.widgets)widget2.last_y-=LiteGraph.NODE_SLOT_HEIGHT;node.setSize([Math.max(sz[0],node.size[0]),Math.max(sz[1],node.size[1])])}__name(convertToWidget,"convertToWidget");function getWidgetType(config){let type=config[0];return type instanceof Array&&(type="COMBO"),{type}}__name(getWidgetType,"getWidgetType");function isValidCombo(combo,obj){return obj instanceof Array?combo.length!==obj.length||combo.find((v,i)=>obj[i]!==v)?(console.log("connection rejected: combo lists dont match"),!1):!0:(console.log(`connection rejected: tried to connect combo to ${obj}`),!1)}__name(isValidCombo,"isValidCombo");function isPrimitiveNode(node){return node.type==="PrimitiveNode"}__name(isPrimitiveNode,"isPrimitiveNode");function setWidgetConfig(slot,config,target){if(slot.widget&&(config?(slot.widget[GET_CONFIG]=()=>config,slot.widget[TARGET]=target):delete slot.widget,slot.link)){const link=app.graph.links[slot.link];if(link){const originNode=app.graph.getNodeById(link.origin_id);isPrimitiveNode(originNode)&&(config?originNode.recreateWidget():app.configuringGraph||(originNode.disconnectOutput(0),originNode.onLastDisconnect()))}}}__name(setWidgetConfig,"setWidgetConfig");function mergeIfValid(output,config2,forceUpdate,recreateWidget,config1){var _a,_b,_c,_d,_e,_f;if(config1||(config1=(_a=output.widget[CONFIG])!=null?_a:output.widget[GET_CONFIG]()),config1[0]instanceof Array){if(!isValidCombo(config1[0],config2[0]))return}else if(config1[0]!==config2[0]){console.log("connection rejected: types dont match",config1[0],config2[0]);return}const keys=new Set([...Object.keys((_b=config1[1])!=null?_b:{}),...Object.keys((_c=config2[1])!=null?_c:{})]);let customConfig;const getCustomConfig=__name(()=>{var _a2,_b2;return customConfig||(typeof structuredClone=="undefined"?customConfig=JSON.parse(JSON.stringify((_a2=config1[1])!=null?_a2:{})):customConfig=structuredClone((_b2=config1[1])!=null?_b2:{})),customConfig},"getCustomConfig"),isNumber=config1[0]==="INT"||config1[0]==="FLOAT";for(const k of keys.values())if(k!=="default"&&k!=="forceInput"&&k!=="defaultInput"&&k!=="control_after_generate"&&k!=="multiline"&&k!=="tooltip"){let v1=config1[1][k],v2=(_d=config2[1])==null?void 0:_d[k];if(v1===v2||!v1&&!v2)continue;if(isNumber){if(k==="min"){const theirMax=(_e=config2[1])==null?void 0:_e.max;if(theirMax!=null&&v1>theirMax){console.log("connection rejected: min > max",v1,theirMax);return}getCustomConfig()[k]=v1==null?v2:v2==null?v1:Math.max(v1,v2);continue}else if(k==="max"){const theirMin=(_f=config2[1])==null?void 0:_f.min;if(theirMin!=null&&v1max&&(widget.value=max),widget.callback(widget.value)}}return{customConfig}}__name(mergeIfValid,"mergeIfValid");let useConversionSubmenusSetting;app.registerExtension({name:"Comfy.WidgetInputs",init(){useConversionSubmenusSetting=app.ui.settings.addSetting({id:"Comfy.NodeInputConversionSubmenus",name:"Node widget/input conversion sub-menus",tooltip:"In the node context menu, place the entries that convert between input/widget in sub-menus.",type:"boolean",defaultValue:!0})},beforeRegisterNodeDef(nodeType,nodeData,app2){return __async(this,null,function*(){const origGetExtraMenuOptions=nodeType.prototype.getExtraMenuOptions;nodeType.prototype.convertWidgetToInput=function(widget){var _a;const config=(_a=getConfig.call(this,widget.name))!=null?_a:[widget.type,widget.options||{}];return isConvertibleWidget(widget,config)?(convertToInput(this,widget,config),!0):!1},nodeType.prototype.getExtraMenuOptions=function(_,options){var _a,_b;const r=origGetExtraMenuOptions?origGetExtraMenuOptions.apply(this,arguments):void 0;if(this.widgets){let toInput=[],toWidget=[];for(const w of this.widgets)if(!((_a=w.options)!=null&&_a.forceInput))if(w.type===CONVERTED_TYPE)toWidget.push({content:`Convert ${w.name} to widget`,callback:__name(()=>convertToWidget(this,w),"callback")});else{const config=(_b=getConfig.call(this,w.name))!=null?_b:[w.type,w.options||{}];isConvertibleWidget(w,config)&&toInput.push({content:`Convert ${w.name} to input`,callback:__name(()=>convertToInput(this,w,config),"callback")})}toInput.length&&(useConversionSubmenusSetting.value?options.push({content:"Convert Widget to Input",submenu:{options:toInput}}):options.push(...toInput,null)),toWidget.length&&(useConversionSubmenusSetting.value?options.push({content:"Convert Input to Widget",submenu:{options:toWidget}}):options.push(...toWidget,null))}return r},nodeType.prototype.onGraphConfigured=function(){if(this.inputs){for(const input of this.inputs)if(input.widget){if(input.widget[GET_CONFIG]||(input.widget[GET_CONFIG]=()=>getConfig.call(this,input.widget.name)),input.widget.config){if(input.widget.config[0]instanceof Array){input.type="COMBO";const link=app2.graph.links[input.link];link&&(link.type=input.type)}delete input.widget.config}const w=this.widgets.find(w2=>w2.name===input.widget.name);w?hideWidget(this,w):convertToWidget(this,input)}}};const origOnNodeCreated=nodeType.prototype.onNodeCreated;nodeType.prototype.onNodeCreated=function(){var _a,_b,_c;const r=origOnNodeCreated?origOnNodeCreated.apply(this):void 0;if(!app2.configuringGraph&&this.widgets){for(const w of this.widgets)if((_a=w==null?void 0:w.options)!=null&&_a.forceInput||(_b=w==null?void 0:w.options)!=null&&_b.defaultInput){const config=(_c=getConfig.call(this,w.name))!=null?_c:[w.type,w.options||{}];convertToInput(this,w,config)}}return r};const origOnConfigure=nodeType.prototype.onConfigure;nodeType.prototype.onConfigure=function(){const r=origOnConfigure?origOnConfigure.apply(this,arguments):void 0;if(!app2.configuringGraph&&this.inputs){for(const input of this.inputs)if(input.widget&&!input.widget[GET_CONFIG]){input.widget[GET_CONFIG]=()=>getConfig.call(this,input.widget.name);const w=this.widgets.find(w2=>w2.name===input.widget.name);w&&hideWidget(this,w)}}return r};function isNodeAtPos(pos){for(const n of app2.graph._nodes)if(n.pos[0]===pos[0]&&n.pos[1]===pos[1])return!0;return!1}__name(isNodeAtPos,"isNodeAtPos");const origOnInputDblClick=nodeType.prototype.onInputDblClick,ignoreDblClick=Symbol();nodeType.prototype.onInputDblClick=function(slot){var _a,_b,_c;const r=origOnInputDblClick?origOnInputDblClick.apply(this,arguments):void 0,input=this.inputs[slot];if((!input.widget||!input[ignoreDblClick])&&!(input.type in ComfyWidgets)&&!(((_c=(_b=(_a=input.widget)[GET_CONFIG])==null?void 0:_b.call(_a))==null?void 0:_c[0])instanceof Array))return r;const node=LiteGraph.createNode("PrimitiveNode");app2.graph.add(node);const pos=[this.pos[0]-node.size[0]-30,this.pos[1]];for(;isNodeAtPos(pos);)pos[1]+=LiteGraph.NODE_TITLE_HEIGHT;return node.pos=pos,node.connect(0,this,slot),node.title=input.name,input[ignoreDblClick]=!0,setTimeout(()=>{delete input[ignoreDblClick]},300),r};const onConnectInput=nodeType.prototype.onConnectInput;nodeType.prototype.onConnectInput=function(targetSlot,type,output,originNode,originSlot){var _a,_b,_c,_d,_e,_f;const v=onConnectInput==null?void 0:onConnectInput(this,arguments);if(type!=="COMBO"||originNode.outputs[originSlot].widget)return v;const targetCombo=(_c=(_b=(_a=this.inputs[targetSlot].widget)==null?void 0:_a[GET_CONFIG])==null?void 0:_b.call(_a))==null?void 0:_c[0];if(!targetCombo||!(targetCombo instanceof Array))return v;const originConfig=(_f=(_e=(_d=originNode.constructor)==null?void 0:_d.nodeData)==null?void 0:_e.output)==null?void 0:_f[originSlot];return!originConfig||!isValidCombo(targetCombo,originConfig)?!1:v}})},registerCustomNodes(){LiteGraph.registerNodeType("PrimitiveNode",Object.assign(PrimitiveNode,{title:"Primitive"})),PrimitiveNode.category="utils"}});window.comfyAPI=window.comfyAPI||{};window.comfyAPI.widgetInputs=window.comfyAPI.widgetInputs||{};window.comfyAPI.widgetInputs.getWidgetConfig=getWidgetConfig;window.comfyAPI.widgetInputs.setWidgetConfig=setWidgetConfig;window.comfyAPI.widgetInputs.mergeIfValid=mergeIfValid;const ORDER=Symbol();function merge(target,source){if(typeof target=="object"&&typeof source=="object")for(const key in source){const sv=source[key];if(typeof sv=="object"){let tv=target[key];tv||(tv=target[key]={}),merge(tv,source[key])}else target[key]=sv}return target}__name(merge,"merge");const _ManageGroupDialog=class _ManageGroupDialog extends ComfyDialog{constructor(app2){super();__publicField(this,"tabs");__publicField(this,"selectedNodeIndex");__publicField(this,"selectedTab","Inputs");__publicField(this,"selectedGroup");__publicField(this,"modifications",{});__publicField(this,"nodeItems");__publicField(this,"app");__publicField(this,"groupNodeType");__publicField(this,"groupNodeDef");__publicField(this,"groupData");__publicField(this,"innerNodesList");__publicField(this,"widgetsPage");__publicField(this,"inputsPage");__publicField(this,"outputsPage");__publicField(this,"draggable");this.app=app2,this.element=$el("dialog.comfy-group-manage",{parent:document.body})}get selectedNodeInnerIndex(){return+this.nodeItems[this.selectedNodeIndex].dataset.nodeindex}changeTab(tab){this.tabs[this.selectedTab].tab.classList.remove("active"),this.tabs[this.selectedTab].page.classList.remove("active"),this.tabs[tab].tab.classList.add("active"),this.tabs[tab].page.classList.add("active"),this.selectedTab=tab}changeNode(index,force){!force&&this.selectedNodeIndex===index||(this.selectedNodeIndex!=null&&this.nodeItems[this.selectedNodeIndex].classList.remove("selected"),this.nodeItems[index].classList.add("selected"),this.selectedNodeIndex=index,!this.buildInputsPage()&&this.selectedTab==="Inputs"&&this.changeTab("Widgets"),!this.buildWidgetsPage()&&this.selectedTab==="Widgets"&&this.changeTab("Outputs"),!this.buildOutputsPage()&&this.selectedTab==="Outputs"&&this.changeTab("Inputs"),this.changeTab(this.selectedTab))}getGroupData(){this.groupNodeType=LiteGraph.registered_node_types["workflow/"+this.selectedGroup],this.groupNodeDef=this.groupNodeType.nodeData,this.groupData=GroupNodeHandler.getGroupData(this.groupNodeType)}changeGroup(group,reset=!0){var _a;this.selectedGroup=group,this.getGroupData();const nodes=this.groupData.nodeData.nodes;if(this.nodeItems=nodes.map((n,i)=>{var _a2;return $el("li.draggable-item",{dataset:{nodeindex:n.index+""},onclick:__name(()=>{this.changeNode(i)},"onclick")},[$el("span.drag-handle"),$el("div",{textContent:(_a2=n.title)!=null?_a2:n.type},n.title?$el("span",{textContent:n.type}):[])])}),this.innerNodesList.replaceChildren(...this.nodeItems),reset)this.selectedNodeIndex=null,this.changeNode(0);else{let index=this.draggable.getAllItems().findIndex(item=>item.classList.contains("selected"));index===-1&&(index=this.selectedNodeIndex),this.changeNode(index,!0)}const ordered=[...nodes];(_a=this.draggable)==null||_a.dispose(),this.draggable=new DraggableList(this.innerNodesList,"li"),this.draggable.addEventListener("dragend",({detail:{oldPosition,newPosition}})=>{if(oldPosition!==newPosition){ordered.splice(newPosition,0,ordered.splice(oldPosition,1)[0]);for(let i=0;i{this.storeModification({section,prop,value:{name:e.target.value}})},"onchange")}),$el("label",{textContent:"Visible"},[$el("input",{type:"checkbox",checked,disabled:!checkable,onchange:__name(e=>{this.storeModification({section,prop,value:{visible:!!e.target.checked}})},"onchange")})])])}buildWidgetsPage(){var _a,_b;const widgets=this.groupData.oldToNewWidgetMap[this.selectedNodeInnerIndex],items=Object.keys(widgets!=null?widgets:{}),config=(_b=(_a=app.graph.extra.groupNodes[this.selectedGroup].config)==null?void 0:_a[this.selectedNodeInnerIndex])==null?void 0:_b.input;return this.widgetsPage.replaceChildren(...items.map(oldName=>{var _a2;return this.getEditElement("input",oldName,widgets[oldName],oldName,((_a2=config==null?void 0:config[oldName])==null?void 0:_a2.visible)!==!1)})),!!items.length}buildInputsPage(){var _a,_b;const inputs=this.groupData.nodeInputs[this.selectedNodeInnerIndex],items=Object.keys(inputs!=null?inputs:{}),config=(_b=(_a=app.graph.extra.groupNodes[this.selectedGroup].config)==null?void 0:_a[this.selectedNodeInnerIndex])==null?void 0:_b.input;return this.inputsPage.replaceChildren(...items.map(oldName=>{var _a2;let value=inputs[oldName];if(value)return this.getEditElement("input",oldName,value,oldName,((_a2=config==null?void 0:config[oldName])==null?void 0:_a2.visible)!==!1)}).filter(Boolean)),!!items.length}buildOutputsPage(){var _a,_b,_c;const nodes=this.groupData.nodeData.nodes,innerNodeDef=this.groupData.getNodeDef(nodes[this.selectedNodeInnerIndex]),outputs=(_a=innerNodeDef==null?void 0:innerNodeDef.output)!=null?_a:[],groupOutputs=this.groupData.oldToNewOutputMap[this.selectedNodeInnerIndex],config=(_c=(_b=app.graph.extra.groupNodes[this.selectedGroup].config)==null?void 0:_b[this.selectedNodeInnerIndex])==null?void 0:_c.output,checkable=this.groupData.nodeData.nodes[this.selectedNodeInnerIndex].type!=="PrimitiveNode";return this.outputsPage.replaceChildren(...outputs.map((type2,slot)=>{var _a2,_b2,_c2,_d;const groupOutputIndex=groupOutputs==null?void 0:groupOutputs[slot],oldName=(_b2=(_a2=innerNodeDef.output_name)==null?void 0:_a2[slot])!=null?_b2:type2;let value=(_c2=config==null?void 0:config[slot])==null?void 0:_c2.name;const visible=((_d=config==null?void 0:config[slot])==null?void 0:_d.visible)||groupOutputIndex!=null;return(!value||value===oldName)&&(value=""),this.getEditElement("output",slot,value,oldName,visible,checkable)}).filter(Boolean)),!!outputs.length}show(type){var _a,_b;const groupNodes=Object.keys((_b=(_a=app.graph.extra)==null?void 0:_a.groupNodes)!=null?_b:{}).sort((a,b)=>a.localeCompare(b));this.innerNodesList=$el("ul.comfy-group-manage-list-items"),this.widgetsPage=$el("section.comfy-group-manage-node-page"),this.inputsPage=$el("section.comfy-group-manage-node-page"),this.outputsPage=$el("section.comfy-group-manage-node-page");const pages=$el("div",[this.widgetsPage,this.inputsPage,this.outputsPage]);this.tabs=[["Inputs",this.inputsPage],["Widgets",this.widgetsPage],["Outputs",this.outputsPage]].reduce((p,[name,page])=>(p[name]={tab:$el("a",{onclick:__name(()=>{this.changeTab(name)},"onclick"),textContent:name}),page},p),{});const outer=$el("div.comfy-group-manage-outer",[$el("header",[$el("h2","Group Nodes"),$el("select",{onchange:__name(e=>{this.changeGroup(e.target.value)},"onchange")},groupNodes.map(g=>$el("option",{textContent:g,selected:"workflow/"+g===type,value:g})))]),$el("main",[$el("section.comfy-group-manage-list",this.innerNodesList),$el("section.comfy-group-manage-node",[$el("header",Object.values(this.tabs).map(t=>t.tab)),pages])]),$el("footer",[$el("button.comfy-btn",{onclick:__name(e=>{if(app.graph._nodes.find(n=>n.type==="workflow/"+this.selectedGroup)){alert("This group node is in use in the current workflow, please first remove these.");return}confirm(`Are you sure you want to remove the node: "${this.selectedGroup}"`)&&(delete app.graph.extra.groupNodes[this.selectedGroup],LiteGraph.unregisterNodeType("workflow/"+this.selectedGroup)),this.show()},"onclick")},"Delete Group Node"),$el("button.comfy-btn",{onclick:__name(()=>__async(this,null,function*(){var _a2,_b2;let nodesByType,recreateNodes=[];const types={};for(const g in this.modifications){const type2=app.graph.extra.groupNodes[g];let config=(_a2=type2.config)!=null?_a2:type2.config={},nodeMods=(_b2=this.modifications[g])==null?void 0:_b2.nodes;if(nodeMods){const keys=Object.keys(nodeMods);if(nodeMods[keys[0]][ORDER]){const orderedNodes=[],orderedMods={},orderedConfig={};for(const n of keys){const order=nodeMods[n][ORDER].order;orderedNodes[order]=type2.nodes[+n],orderedMods[order]=nodeMods[n],orderedNodes[order].index=order}for(const l of type2.links)l[0]!=null&&(l[0]=type2.nodes[l[0]].index),l[2]!=null&&(l[2]=type2.nodes[l[2]].index);if(type2.external)for(const ext2 of type2.external)ext2[0]=type2.nodes[ext2[0]];for(const id2 of keys)config[id2]&&(orderedConfig[type2.nodes[id2].index]=config[id2]),delete config[id2];type2.nodes=orderedNodes,nodeMods=orderedMods,type2.config=config=orderedConfig}merge(config,nodeMods)}types[g]=type2,nodesByType||(nodesByType=app.graph._nodes.reduce((p,n)=>{var _a3,_b3;return(_b3=p[_a3=n.type])!=null||(p[_a3]=[]),p[n.type].push(n),p},{}));const nodes=nodesByType["workflow/"+g];nodes&&recreateNodes.push(...nodes)}yield GroupNodeConfig.registerFromWorkflow(types,{});for(const node of recreateNodes)node.recreate();this.modifications={},this.app.graph.setDirtyCanvas(!0,!0),this.changeGroup(this.selectedGroup,!1)}),"onclick")},"Save"),$el("button.comfy-btn",{onclick:__name(()=>this.element.close(),"onclick")},"Close")])]);this.element.replaceChildren(outer),this.changeGroup(type?groupNodes.find(g=>"workflow/"+g===type):groupNodes[0]),this.element.showModal(),this.element.addEventListener("close",()=>{var _a2;(_a2=this.draggable)==null||_a2.dispose()})}};__name(_ManageGroupDialog,"ManageGroupDialog");let ManageGroupDialog=_ManageGroupDialog;window.comfyAPI=window.comfyAPI||{};window.comfyAPI.groupNodeManage=window.comfyAPI.groupNodeManage||{};window.comfyAPI.groupNodeManage.ManageGroupDialog=ManageGroupDialog;const GROUP=Symbol(),Workflow={InUse:{Free:0,Registered:1,InWorkflow:2},isInUseGroupNode(name){var _a,_b;const id2=`workflow/${name}`;return(_b=(_a=app.graph.extra)==null?void 0:_a.groupNodes)!=null&&_b[name]?app.graph._nodes.find(n=>n.type===id2)?Workflow.InUse.InWorkflow:Workflow.InUse.Registered:Workflow.InUse.Free},storeGroupNode(name,data){let extra=app.graph.extra;extra||(app.graph.extra=extra={});let groupNodes=extra.groupNodes;groupNodes||(extra.groupNodes=groupNodes={}),groupNodes[name]=data}},_GroupNodeBuilder=class _GroupNodeBuilder{constructor(nodes){__publicField(this,"nodes");__publicField(this,"nodeData");this.nodes=nodes}build(){const name=this.getName();if(name)return this.sortNodes(),this.nodeData=this.getNodeData(),Workflow.storeGroupNode(name,this.nodeData),{name,nodeData:this.nodeData}}getName(){const name=prompt("Enter group name");if(!name)return;switch(Workflow.isInUseGroupNode(name)){case Workflow.InUse.InWorkflow:alert("An in use group node with this name already exists embedded in this workflow, please remove any instances or use a new name.");return;case Workflow.InUse.Registered:if(!confirm("A group node with this name already exists embedded in this workflow, are you sure you want to overwrite it?"))return;break}return name}sortNodes(){const nodesInOrder=app.graph.computeExecutionOrder(!1);this.nodes=this.nodes.map(node=>({index:nodesInOrder.indexOf(node),node})).sort((a,b)=>a.index-b.index||a.node.id-b.node.id).map(({node})=>node)}getNodeData(){const storeLinkTypes=__name(config=>{for(const link of config.links){const type=app.graph.getNodeById(link[4]).outputs[link[1]].type;link.push(type)}},"storeLinkTypes"),storeExternalLinks=__name(config=>{var _a,_b;config.external=[];for(let i=0;iinp.name===inputName))==null?void 0:_e.label)!=null?_g:inputName,key=name,prefix="";return(node.type==="PrimitiveNode"&&node.title||name in seenInputs)&&(prefix=`${(_h=node.title)!=null?_h:node.type} `,key=name=`${prefix}${inputName}`,name in seenInputs&&(name=`${prefix}${seenInputs[name]} ${inputName}`)),seenInputs[key]=((_i=seenInputs[key])!=null?_i:1)+1,(inputName==="seed"||inputName==="noise_seed")&&(extra||(extra={}),extra.control_after_generate=`${prefix}control_after_generate`),config[0]==="IMAGEUPLOAD"&&(extra||(extra={}),extra.widget=(_m=(_l=this.oldToNewWidgetMap[node.index])==null?void 0:_l[(_k=(_j=config[1])==null?void 0:_j.widget)!=null?_k:"image"])!=null?_m:"image"),extra&&(config=[config[0],__spreadValues(__spreadValues({},config[1]),extra)]),{name,config,customConfig}}processWidgetInputs(inputs,node,inputNames,seenInputs){var _a;const slots=[],converted=new Map,widgetMap=this.oldToNewWidgetMap[node.index]={};for(const inputName of inputNames)if(app.getWidgetType(inputs[inputName],inputName)){const convertedIndex=(_a=node.inputs)==null?void 0:_a.findIndex(inp=>{var _a2;return inp.name===inputName&&((_a2=inp.widget)==null?void 0:_a2.name)===inputName});if(convertedIndex>-1)converted.set(convertedIndex,inputName),widgetMap[inputName]=null;else{const{name,config}=this.getInputConfig(node,inputName,seenInputs,inputs[inputName]);this.nodeDef.input.required[name]=config,widgetMap[inputName]=name,this.newToOldWidgetMap[name]={node,inputName}}}else slots.push(inputName);return{converted,slots}}checkPrimitiveConnection(link,inputName,inputs){var _a;if(this.nodeData.nodes[link[0]].type==="PrimitiveNode"){const[sourceNodeId,_,targetNodeId,__]=link,primitiveDef=this.primitiveDefs[sourceNodeId],targetWidget=inputs[inputName],primitiveConfig=primitiveDef.input.required.value,config=mergeIfValid({widget:primitiveConfig},targetWidget,!1,null,primitiveConfig);primitiveConfig[1]=((_a=config==null?void 0:config.customConfig)!=null?_a:inputs[inputName][1])?__spreadValues({},inputs[inputName][1]):{};let name=this.oldToNewWidgetMap[sourceNodeId].value;name=name.substr(0,name.length-6),primitiveConfig[1].control_after_generate=!0,primitiveConfig[1].control_prefix=name;let toPrimitive=this.widgetToPrimitive[targetNodeId];toPrimitive||(toPrimitive=this.widgetToPrimitive[targetNodeId]={}),toPrimitive[inputName]&&toPrimitive[inputName].push(sourceNodeId),toPrimitive[inputName]=sourceNodeId;let toWidget=this.primitiveToWidget[sourceNodeId];toWidget||(toWidget=this.primitiveToWidget[sourceNodeId]=[]),toWidget.push({nodeId:targetNodeId,inputName})}}processInputSlots(inputs,node,slots,linksTo,inputMap,seenInputs){this.nodeInputs[node.index]={};for(let i=0;iconverted.get(k));for(let i=0;ithis.processConvertedWidgets(inputs,node,slots,converted,linksTo,inputMap,seenInputs)),inputMapping}processNodeOutputs(node,seenOutputs,def){var _a,_b,_c,_d,_e,_f,_g,_h;const oldToNew=this.oldToNewOutputMap[node.index]={};for(let outputId=0;outputIdo.name===label);output!=null&&output.label&&(label=output.label)}let name=label;if(name in seenOutputs){const prefix=`${(_h=node.title)!=null?_h:node.type} `;name=`${prefix}${label}`,name in seenOutputs&&(name=`${prefix}${node.index} ${label}`)}seenOutputs[name]=1,this.nodeDef.output_name.push(name)}}static registerFromWorkflow(groupNodes,missingNodeTypes){return __async(this,null,function*(){const clean=app.clean;app.clean=function(){for(const g in groupNodes)try{LiteGraph.unregisterNodeType("workflow/"+g)}catch(error){}app.clean=clean};for(const g in groupNodes){const groupData=groupNodes[g];let hasMissing=!1;for(const n of groupData.nodes)n.type in LiteGraph.registered_node_types||(missingNodeTypes.push({type:n.type,hint:` (In group node 'workflow/${g}')`}),missingNodeTypes.push({type:"workflow/"+g,action:{text:"Remove from workflow",callback:__name(e=>{delete groupNodes[g],e.target.textContent="Removed",e.target.style.pointerEvents="none",e.target.style.opacity=.7},"callback")}}),hasMissing=!0);if(hasMissing)continue;yield new _GroupNodeConfig(g,groupData).registerType()}})}};_convertedToProcess=new WeakMap,__name(_GroupNodeConfig,"GroupNodeConfig");let GroupNodeConfig=_GroupNodeConfig;const _GroupNodeHandler=class _GroupNodeHandler{constructor(node){__publicField(this,"node");__publicField(this,"groupData");__publicField(this,"innerNodes");var _a,_b;this.node=node,this.groupData=(_b=(_a=node.constructor)==null?void 0:_a.nodeData)==null?void 0:_b[GROUP],this.node.setInnerNodes=innerNodes=>{var _a2;this.innerNodes=innerNodes;for(let innerNodeIndex=0;innerNodeIndex{var _a3,_b2;const externalSlot=(_a3=this.groupData.oldToNewInputMap[innerNode.index])==null?void 0:_a3[slot];if(externalSlot!=null)return this.node.getInputNode(externalSlot);const innerLink=(_b2=this.groupData.linksTo[innerNode.index])==null?void 0:_b2[slot];if(!innerLink)return null;const inputNode=innerNodes[innerLink[0]];return inputNode.type==="PrimitiveNode"?null:inputNode},innerNode.getInputLink=slot=>{var _a3,_b2;const externalSlot=(_a3=this.groupData.oldToNewInputMap[innerNode.index])==null?void 0:_a3[slot];if(externalSlot!=null){const linkId=this.node.inputs[externalSlot].link;let link2=app.graph.links[linkId];return link2=__spreadProps(__spreadValues({},link2),{target_id:innerNode.id,target_slot:+slot}),link2}let link=(_b2=this.groupData.linksTo[innerNode.index])==null?void 0:_b2[slot];return link?(link={origin_id:innerNodes[link[0]].id,origin_slot:link[1],target_id:innerNode.id,target_slot:+slot},link):null}}},this.node.updateLink=link=>{var _a2;link=__spreadValues({},link);const output=this.groupData.newToOldOutputMap[link.origin_slot];let innerNode=this.innerNodes[output.node.index],l;for(;(innerNode==null?void 0:innerNode.type)==="Reroute";)l=innerNode.getInputLink(0),innerNode=innerNode.getInputNode(0);return innerNode?l&&_GroupNodeHandler.isGroupNode(innerNode)?innerNode.updateLink(l):(link.origin_id=innerNode.id,link.origin_slot=(_a2=l==null?void 0:l.origin_slot)!=null?_a2:output.slot,link):null},this.node.getInnerNodes=()=>(this.innerNodes||this.node.setInnerNodes(this.groupData.nodeData.nodes.map((n,i)=>{const innerNode=LiteGraph.createNode(n.type);return innerNode.configure(n),innerNode.id=`${this.node.id}:${i}`,innerNode})),this.updateInnerWidgets(),this.innerNodes),this.node.recreate=()=>__async(this,null,function*(){const id2=this.node.id,sz=this.node.size,nodes=this.node.convertToNodes(),groupNode=LiteGraph.createNode(this.node.type);return groupNode.id=id2,groupNode.setInnerNodes(nodes),groupNode[GROUP].populateWidgets(),app.graph.add(groupNode),groupNode.size=[Math.max(groupNode.size[0],sz[0]),Math.max(groupNode.size[1],sz[1])],groupNode[GROUP].replaceNodes(nodes),groupNode}),this.node.convertToNodes=()=>{const addInnerNodes=__name(()=>{var _a2,_b2;const backup=localStorage.getItem("litegrapheditor_clipboard"),c=__spreadValues({},this.groupData.nodeData);c.nodes=[...c.nodes];const innerNodes=this.node.getInnerNodes();let ids=[];for(let i=0;iw.name===newName);if(widgetIndex!==-1)if(innerNode.type==="PrimitiveNode")for(let i2=0;i2w.name===oldName);if(!newWidget)continue;newWidget.value=outerWidget.value;for(let w=0;w<((_b2=outerWidget.linkedWidgets)==null?void 0:_b2.length);w++)newWidget.linkedWidgets[w].value=outerWidget.linkedWidgets[w].value}}}}for(const newNode of newNodes2)newNode.pos=[newNode.pos[0]-(left-x),newNode.pos[1]-(top-y)];return{newNodes:newNodes2,selectedIds:selectedIds2}},"addInnerNodes"),reconnectInputs=__name(selectedIds2=>{for(const innerNodeIndex in this.groupData.oldToNewInputMap){const id2=selectedIds2[innerNodeIndex],newNode=app.graph.getNodeById(id2),map=this.groupData.oldToNewInputMap[innerNodeIndex];for(const innerInputId in map){const groupSlotId=map[innerInputId];if(groupSlotId==null)continue;const slot=node.inputs[groupSlotId];if(slot.link==null)continue;const link=app.graph.links[slot.link];if(!link)continue;app.graph.getNodeById(link.origin_id).connect(link.origin_slot,newNode,+innerInputId)}}},"reconnectInputs"),reconnectOutputs=__name(selectedIds2=>{var _a2;for(let groupOutputId=0;groupOutputId<((_a2=node.outputs)==null?void 0:_a2.length);groupOutputId++){const output=node.outputs[groupOutputId];if(!output.links)continue;const links=[...output.links];for(const l of links){const slot=this.groupData.newToOldOutputMap[groupOutputId],link=app.graph.links[l],targetNode=app.graph.getNodeById(link.target_id);app.graph.getNodeById(selectedIds2[slot.node.index]).connect(slot.slot,targetNode,link.target_slot)}}},"reconnectOutputs"),{newNodes,selectedIds}=addInnerNodes();return reconnectInputs(selectedIds),reconnectOutputs(selectedIds),app.graph.remove(this.node),newNodes};const getExtraMenuOptions=this.node.getExtraMenuOptions;this.node.getExtraMenuOptions=function(_,options){getExtraMenuOptions==null||getExtraMenuOptions.apply(this,arguments);let optionIndex=options.findIndex(o=>o.content==="Outputs");optionIndex===-1?optionIndex=options.length:optionIndex++,options.splice(optionIndex,0,null,{content:"Convert to nodes",callback:__name(()=>this.convertToNodes(),"callback")},{content:"Manage Group Node",callback:__name(()=>{new ManageGroupDialog(app).show(this.type)},"callback")})};const onDrawTitleBox=this.node.onDrawTitleBox;this.node.onDrawTitleBox=function(ctx,height,size,scale){onDrawTitleBox==null||onDrawTitleBox.apply(this,arguments);const fill=ctx.fillStyle;ctx.beginPath(),ctx.rect(11,-height+11,2,2),ctx.rect(14,-height+11,2,2),ctx.rect(17,-height+11,2,2),ctx.rect(11,-height+14,2,2),ctx.rect(14,-height+14,2,2),ctx.rect(17,-height+14,2,2),ctx.rect(11,-height+17,2,2),ctx.rect(14,-height+17,2,2),ctx.rect(17,-height+17,2,2),ctx.fillStyle=this.boxcolor||LiteGraph.NODE_DEFAULT_BOXCOLOR,ctx.fill(),ctx.fillStyle=fill};const onDrawForeground=node.onDrawForeground,groupData=this.groupData.nodeData;node.onDrawForeground=function(ctx){var _a2;const r=(_a2=onDrawForeground==null?void 0:onDrawForeground.apply)==null?void 0:_a2.call(onDrawForeground,this,arguments);if(+app.runningNodeId===this.id&&this.runningInternalNodeId!==null){const n=groupData.nodes[this.runningInternalNodeId];if(!n)return;const message=`Running ${n.title||n.type} (${this.runningInternalNodeId}/${groupData.nodes.length})`;ctx.save(),ctx.font="12px sans-serif";const sz=ctx.measureText(message);ctx.fillStyle=node.boxcolor||LiteGraph.NODE_DEFAULT_BOXCOLOR,ctx.beginPath(),ctx.roundRect(0,-LiteGraph.NODE_TITLE_HEIGHT-20,sz.width+12,20,5),ctx.fill(),ctx.fillStyle="#fff",ctx.fillText(message,6,-LiteGraph.NODE_TITLE_HEIGHT-6),ctx.restore()}};const onExecutionStart=this.node.onExecutionStart;this.node.onExecutionStart=function(){return this.resetExecution=!0,onExecutionStart==null?void 0:onExecutionStart.apply(this,arguments)};const self=this,onNodeCreated=this.node.onNodeCreated;this.node.onNodeCreated=function(){var _a2;if(!this.widgets)return;const config=self.groupData.nodeData.config;if(config)for(const n in config){const inputs=(_a2=config[n])==null?void 0:_a2.input;for(const w in inputs){if(inputs[w].visible!==!1)continue;const widgetName=self.groupData.oldToNewWidgetMap[n][w],widget=this.widgets.find(w2=>w2.name===widgetName);widget&&(widget.type="hidden",widget.computeSize=()=>[0,-4])}}return onNodeCreated==null?void 0:onNodeCreated.apply(this,arguments)};function handleEvent(type,getId,getEvent){const handler=__name(({detail})=>{var _a2;const id2=getId(detail);if(!id2||app.graph.getNodeById(id2))return;const innerNodeIndex=(_a2=this.innerNodes)==null?void 0:_a2.findIndex(n=>n.id==id2);innerNodeIndex>-1&&(this.node.runningInternalNodeId=innerNodeIndex,api.dispatchEvent(new CustomEvent(type,{detail:getEvent(detail,this.node.id+"",this.node)})))},"handler");return api.addEventListener(type,handler),handler}__name(handleEvent,"handleEvent");const executing=handleEvent.call(this,"executing",d=>d,(d,id2,node2)=>id2),executed=handleEvent.call(this,"executed",d=>(d==null?void 0:d.display_node)||(d==null?void 0:d.node),(d,id2,node2)=>__spreadProps(__spreadValues({},d),{node:id2,display_node:id2,merge:!node2.resetExecution})),onRemoved=node.onRemoved;this.node.onRemoved=function(){onRemoved==null||onRemoved.apply(this,arguments),api.removeEventListener("executing",executing),api.removeEventListener("executed",executed)},this.node.refreshComboInNode=defs=>{var _a2,_b2,_c,_d,_e;for(const widgetName in this.groupData.newToOldWidgetMap){const widget=this.node.widgets.find(w=>w.name===widgetName);if((widget==null?void 0:widget.type)==="combo"){const old=this.groupData.newToOldWidgetMap[widgetName],def=defs[old.node.type],input=(_e=(_b2=(_a2=def==null?void 0:def.input)==null?void 0:_a2.required)==null?void 0:_b2[old.inputName])!=null?_e:(_d=(_c=def==null?void 0:def.input)==null?void 0:_c.optional)==null?void 0:_d[old.inputName];if(!input)continue;widget.options.values=input[0],old.inputName!=="image"&&!widget.options.values.includes(widget.value)&&(widget.value=widget.options.values[0],widget.callback(widget.value))}}}}updateInnerWidgets(){var _a,_b;for(const newWidgetName in this.groupData.newToOldWidgetMap){const newWidget=this.node.widgets.find(w=>w.name===newWidgetName);if(!newWidget)continue;const newValue=newWidget.value,old=this.groupData.newToOldWidgetMap[newWidgetName];let innerNode=this.innerNodes[old.node.index];if(innerNode.type==="PrimitiveNode"){innerNode.primitiveValue=newValue;const primitiveLinked=this.groupData.primitiveToWidget[old.node.index];for(const linked of primitiveLinked!=null?primitiveLinked:[]){const widget2=this.innerNodes[linked.nodeId].widgets.find(w=>w.name===linked.inputName);widget2&&(widget2.value=newValue)}continue}else if(innerNode.type==="Reroute"){const rerouteLinks=this.groupData.linksFrom[old.node.index];if(rerouteLinks)for(const[_,,targetNodeId,targetSlot]of rerouteLinks[0]){const node=this.innerNodes[targetNodeId],input=node.inputs[targetSlot];if(input.widget){const widget2=(_a=node.widgets)==null?void 0:_a.find(w=>w.name===input.widget.name);widget2&&(widget2.value=newValue)}}}const widget=(_b=innerNode.widgets)==null?void 0:_b.find(w=>w.name===old.inputName);widget&&(widget.value=newValue)}}populatePrimitive(node,nodeId,oldName,i,linkedShift){var _a,_b;const primitiveId=(_a=this.groupData.widgetToPrimitive[nodeId])==null?void 0:_a[oldName];if(primitiveId==null)return;const targetWidgetName=this.groupData.oldToNewWidgetMap[primitiveId].value,targetWidgetIndex=this.node.widgets.findIndex(w=>w.name===targetWidgetName);if(targetWidgetIndex>-1){const primitiveNode=this.innerNodes[primitiveId];let len=primitiveNode.widgets.length;len-1!==((_b=this.node.widgets[targetWidgetIndex].linkedWidgets)==null?void 0:_b.length)&&(len=1);for(let i2=0;i2w.name===widgetName);widget&&(widget.value=v)}populateWidgets(){var _a,_b,_c,_d,_e,_f;if(this.node.widgets)for(let nodeId=0;nodeIdw.name===newName),mainWidget=this.node.widgets[widgetIndex];if(this.populatePrimitive(node,nodeId,oldName,i,linkedShift)||widgetIndex===-1){const innerWidget=(_c=this.innerNodes[nodeId].widgets)==null?void 0:_c.find(w=>w.name===oldName);linkedShift+=(_e=(_d=innerWidget==null?void 0:innerWidget.linkedWidgets)==null?void 0:_d.length)!=null?_e:0}if(widgetIndex!==-1){mainWidget.value=node.widgets_values[i+linkedShift];for(let w=0;w<((_f=mainWidget.linkedWidgets)==null?void 0:_f.length);w++)this.node.widgets[widgetIndex+w+1].value=node.widgets_values[i+ ++linkedShift]}}}}replaceNodes(nodes){let top,left;for(let i=0;iGroupNodeHandler.isGroupNode(n));options.splice(index+1,null,{content:"Convert to Group Node",disabled,callback:__name(()=>__async(this,null,function*(){return yield GroupNodeHandler.fromNodes(selected)}),"callback")})}__name(addConvertOption,"addConvertOption");function addManageOption(options,index){var _a;const groups=(_a=app.graph.extra)==null?void 0:_a.groupNodes,disabled=!groups||!Object.keys(groups).length;options.splice(index+1,null,{content:"Manage Group Nodes",disabled,callback:__name(()=>{new ManageGroupDialog(app).show()},"callback")})}__name(addManageOption,"addManageOption");const getCanvasMenuOptions=LGraphCanvas.prototype.getCanvasMenuOptions;LGraphCanvas.prototype.getCanvasMenuOptions=function(){const options=getCanvasMenuOptions.apply(this,arguments),index=options.findIndex(o=>(o==null?void 0:o.content)==="Add Group")+1||options.length;return addConvertOption(options,index),addManageOption(options,index+1),options};const getNodeMenuOptions=LGraphCanvas.prototype.getNodeMenuOptions;LGraphCanvas.prototype.getNodeMenuOptions=function(node){const options=getNodeMenuOptions.apply(this,arguments);if(!GroupNodeHandler.isGroupNode(node)){const index=options.findIndex(o=>(o==null?void 0:o.content)==="Outputs")+1||options.length-1;addConvertOption(options,index)}return options}}__name(addConvertToGroupOptions,"addConvertToGroupOptions");const id$3="Comfy.GroupNode";let globalDefs;const ext$1={name:id$3,setup(){addConvertToGroupOptions()},beforeConfigureGraph(graphData,missingNodeTypes){return __async(this,null,function*(){var _a;const nodes=(_a=graphData==null?void 0:graphData.extra)==null?void 0:_a.groupNodes;nodes&&(yield GroupNodeConfig.registerFromWorkflow(nodes,missingNodeTypes))})},addCustomNodeDefs(defs){globalDefs=defs},nodeCreated(node){GroupNodeHandler.isGroupNode(node)&&(node[GROUP]=new GroupNodeHandler(node))},refreshComboInNodes(defs){return __async(this,null,function*(){var _a;Object.assign(globalDefs,defs);const nodes=(_a=app.graph.extra)==null?void 0:_a.groupNodes;nodes&&(yield GroupNodeConfig.registerFromWorkflow(nodes,{}))})}};app.registerExtension(ext$1);window.comfyAPI=window.comfyAPI||{};window.comfyAPI.groupNode=window.comfyAPI.groupNode||{};window.comfyAPI.groupNode.GroupNodeConfig=GroupNodeConfig;window.comfyAPI.groupNode.GroupNodeHandler=GroupNodeHandler;function setNodeMode(node,mode){node.mode=mode,node.graph.change()}__name(setNodeMode,"setNodeMode");function addNodesToGroup(group,nodes=[]){var _a;var x1,y1,x2,y2,nx1,ny1,nx2,ny2,node;x1=y1=x2=y2=-1,nx1=ny1=nx2=ny2=-1;for(var n of[group._nodes,nodes])for(var i in n)node=n[i],nx1=node.pos[0],ny1=node.pos[1],nx2=node.pos[0]+node.size[0],ny2=node.pos[1]+node.size[1],node.type!="Reroute"&&(ny1-=LiteGraph.NODE_TITLE_HEIGHT),(_a=node.flags)!=null&&_a.collapsed&&(ny2=ny1+LiteGraph.NODE_TITLE_HEIGHT,node!=null&&node._collapsed_width&&(nx2=nx1+Math.round(node._collapsed_width))),(x1==-1||nx1x2)&&(x2=nx2),(y2==-1||ny2>y2)&&(y2=ny2);var padding=10;y1=y1-Math.round(group.font_size*1.4),group.pos=[x1-padding,y1-padding],group.size=[x2-x1+padding*2,y2-y1+padding*2]}__name(addNodesToGroup,"addNodesToGroup");app.registerExtension({name:"Comfy.GroupOptions",setup(){const orig=LGraphCanvas.prototype.getCanvasMenuOptions;LGraphCanvas.prototype.getCanvasMenuOptions=function(){const options=orig.apply(this,arguments),group=this.graph.getGroupOnPos(this.graph_mouse[0],this.graph_mouse[1]);if(!group)return options.push({content:"Add Group For Selected Nodes",disabled:!Object.keys(app.canvas.selected_nodes||{}).length,callback:__name(()=>{var group2=new LiteGraph.LGraphGroup;addNodesToGroup(group2,this.selected_nodes),app.canvas.graph.add(group2),this.graph.change()},"callback")}),options;group.recomputeInsideNodes();const nodesInGroup=group._nodes;if(options.push({content:"Add Selected Nodes To Group",disabled:!Object.keys(app.canvas.selected_nodes||{}).length,callback:__name(()=>{addNodesToGroup(group,this.selected_nodes),this.graph.change()},"callback")}),nodesInGroup.length===0)return options;options.push(null);let allNodesAreSameMode=!0;for(let i=1;i{addNodesToGroup(group),this.graph.change()},"callback")}),options.push({content:"Select Nodes",callback:__name(()=>{this.selectNodes(nodesInGroup),this.graph.change(),this.canvas.focus()},"callback")}),allNodesAreSameMode)switch(nodesInGroup[0].mode){case 0:options.push({content:"Set Group Nodes to Never",callback:__name(()=>{for(const node of nodesInGroup)setNodeMode(node,2)},"callback")}),options.push({content:"Bypass Group Nodes",callback:__name(()=>{for(const node of nodesInGroup)setNodeMode(node,4)},"callback")});break;case 2:options.push({content:"Set Group Nodes to Always",callback:__name(()=>{for(const node of nodesInGroup)setNodeMode(node,0)},"callback")}),options.push({content:"Bypass Group Nodes",callback:__name(()=>{for(const node of nodesInGroup)setNodeMode(node,4)},"callback")});break;case 4:options.push({content:"Set Group Nodes to Always",callback:__name(()=>{for(const node of nodesInGroup)setNodeMode(node,0)},"callback")}),options.push({content:"Set Group Nodes to Never",callback:__name(()=>{for(const node of nodesInGroup)setNodeMode(node,2)},"callback")});break;default:options.push({content:"Set Group Nodes to Always",callback:__name(()=>{for(const node of nodesInGroup)setNodeMode(node,0)},"callback")}),options.push({content:"Set Group Nodes to Never",callback:__name(()=>{for(const node of nodesInGroup)setNodeMode(node,2)},"callback")}),options.push({content:"Bypass Group Nodes",callback:__name(()=>{for(const node of nodesInGroup)setNodeMode(node,4)},"callback")});break}else options.push({content:"Set Group Nodes to Always",callback:__name(()=>{for(const node of nodesInGroup)setNodeMode(node,0)},"callback")}),options.push({content:"Set Group Nodes to Never",callback:__name(()=>{for(const node of nodesInGroup)setNodeMode(node,2)},"callback")}),options.push({content:"Bypass Group Nodes",callback:__name(()=>{for(const node of nodesInGroup)setNodeMode(node,4)},"callback")});return options}}});const id$2="Comfy.InvertMenuScrolling";app.registerExtension({name:id$2,init(){const ctxMenu=LiteGraph.ContextMenu,replace=__name(()=>{LiteGraph.ContextMenu=function(values,options){return options=options||{},options.scroll_speed?options.scroll_speed*=-1:options.scroll_speed=-.1,ctxMenu.call(this,values,options)},LiteGraph.ContextMenu.prototype=ctxMenu.prototype},"replace");app.ui.settings.addSetting({id:id$2,name:"Invert Menu Scrolling",type:"boolean",defaultValue:!1,onChange(value){value?replace():LiteGraph.ContextMenu=ctxMenu}})}});app.registerExtension({name:"Comfy.Keybinds",init(){const keybindListener=__name(function(event){const modifierPressed=event.ctrlKey||event.metaKey;if(modifierPressed&&event.key==="Enter"){if(event.altKey){api.interrupt();return}app.queuePrompt(event.shiftKey?-1:0).then();return}const target=event.composedPath()[0];if(["INPUT","TEXTAREA"].includes(target.tagName))return;const modifierKeybindId={s:"#comfy-save-button",o:"#comfy-file-input",Backspace:"#comfy-clear-button",d:"#comfy-load-default-button"}[event.key];if(modifierPressed&&modifierKeybindId){event.preventDefault(),document.querySelector(modifierKeybindId).click();return}if(event.ctrlKey||event.altKey||event.metaKey)return;if(event.key==="Escape"){const modals=document.querySelectorAll(".comfy-modal"),modal=Array.from(modals).find(modal2=>window.getComputedStyle(modal2).getPropertyValue("display")!=="none");modal&&(modal.style.display="none"),[...document.querySelectorAll("dialog")].forEach(d=>{d.close()})}const buttonId={q:".queue-tab-button.side-bar-button",h:".queue-tab-button.side-bar-button",r:"#comfy-refresh-button"}[event.key];buttonId&&document.querySelector(buttonId).click()},"keybindListener");window.addEventListener("keydown",keybindListener,!0)}});const id$1="Comfy.LinkRenderMode",ext={name:id$1,setup(app2){return __async(this,null,function*(){app2.ui.settings.addSetting({id:id$1,name:"Link Render Mode",defaultValue:2,type:"combo",options:[...LiteGraph.LINK_RENDER_MODES,"Hidden"].map((m,i)=>({value:i,text:m,selected:i==app2.canvas.links_render_mode})),onChange(value){app2.canvas.links_render_mode=+value,app2.graph.setDirtyCanvas(!0)}})})}};app.registerExtension(ext);function dataURLToBlob(dataURL){const parts=dataURL.split(";base64,"),contentType=parts[0].split(":")[1],byteString=atob(parts[1]),arrayBuffer=new ArrayBuffer(byteString.length),uint8Array=new Uint8Array(arrayBuffer);for(let i=0;i{const image=new Image;image.onload=function(){resolve(image)},image.src=imagePath})}__name(loadImage,"loadImage");function uploadMask(filepath,formData){return __async(this,null,function*(){yield api.fetchApi("/upload/mask",{method:"POST",body:formData}).then(response=>{}).catch(error=>{console.error("Error:",error)}),ComfyApp.clipspace.imgs[ComfyApp.clipspace.selectedIndex]=new Image,ComfyApp.clipspace.imgs[ComfyApp.clipspace.selectedIndex].src=api.apiURL("/view?"+new URLSearchParams(filepath).toString()+app.getPreviewFormatParam()+app.getRandParam()),ComfyApp.clipspace.images&&(ComfyApp.clipspace.images[ComfyApp.clipspace.selectedIndex]=filepath),ClipspaceDialog.invalidatePreview()})}__name(uploadMask,"uploadMask");function prepare_mask(image,maskCanvas,maskCtx,maskColor){maskCtx.drawImage(image,0,0,maskCanvas.width,maskCanvas.height);const maskData=maskCtx.getImageData(0,0,maskCanvas.width,maskCanvas.height);for(let i=0;i{self.maskCtx.clearRect(0,0,self.maskCanvas.width,self.maskCanvas.height)});this.brush_size_slider=this.createLeftSlider(self,"Thickness",event=>{self.brush_size=event.target.value,self.updateBrushPreview(self)}),this.brush_opacity_slider=this.createOpacitySlider(self,"Opacity",event=>{self.brush_opacity=event.target.value,self.brush_color_mode!=="negative"&&(self.maskCanvas.style.opacity=self.brush_opacity.toString())}),this.colorButton=this.createLeftButton(this.getColorButtonText(),()=>{self.brush_color_mode==="black"?self.brush_color_mode="white":self.brush_color_mode==="white"?self.brush_color_mode="negative":self.brush_color_mode="black",self.updateWhenBrushColorModeChanged()});var cancelButton=this.createRightButton("Cancel",()=>{document.removeEventListener("keydown",_MaskEditorDialog.handleKeyDown),self.close()});this.saveButton=this.createRightButton("Save",()=>{document.removeEventListener("keydown",_MaskEditorDialog.handleKeyDown),self.save()}),this.element.appendChild(imgCanvas),this.element.appendChild(maskCanvas),this.element.appendChild(bottom_panel),bottom_panel.appendChild(clearButton),bottom_panel.appendChild(this.saveButton),bottom_panel.appendChild(cancelButton),bottom_panel.appendChild(this.brush_size_slider),bottom_panel.appendChild(this.brush_opacity_slider),bottom_panel.appendChild(this.colorButton),imgCanvas.style.position="absolute",maskCanvas.style.position="absolute",imgCanvas.style.top="200",imgCanvas.style.left="0",maskCanvas.style.top=imgCanvas.style.top,maskCanvas.style.left=imgCanvas.style.left;const maskCanvasStyle=this.getMaskCanvasStyle();maskCanvas.style.mixBlendMode=maskCanvasStyle.mixBlendMode,maskCanvas.style.opacity=maskCanvasStyle.opacity.toString()}show(){return __async(this,null,function*(){if(this.zoom_ratio=1,this.pan_x=0,this.pan_y=0,!this.is_layout_created){const imgCanvas=document.createElement("canvas"),maskCanvas=document.createElement("canvas");imgCanvas.id="imageCanvas",maskCanvas.id="maskCanvas",this.setlayout(imgCanvas,maskCanvas),this.imgCanvas=imgCanvas,this.maskCanvas=maskCanvas,this.maskCtx=maskCanvas.getContext("2d",{willReadFrequently:!0}),this.setEventHandler(maskCanvas),this.is_layout_created=!0;const self=this,observer=new MutationObserver(function(mutations){mutations.forEach(function(mutation){mutation.type==="attributes"&&mutation.attributeName==="style"&&(self.last_display_style&&self.last_display_style!="none"&&self.element.style.display=="none"&&(self.brush.style.display="none",ComfyApp.onClipspaceEditorClosed()),self.last_display_style=self.element.style.display)})}),config={attributes:!0};observer.observe(this.element,config)}document.addEventListener("keydown",_MaskEditorDialog.handleKeyDown),ComfyApp.clipspace_return_node?this.saveButton.innerText="Save to node":this.saveButton.innerText="Save",this.saveButton.disabled=!1,this.element.style.display="block",this.element.style.width="85%",this.element.style.margin="0 7.5%",this.element.style.height="100vh",this.element.style.top="50%",this.element.style.left="42%",this.element.style.zIndex="8888",yield this.setImages(this.imgCanvas),this.is_visible=!0})}isOpened(){return this.element.style.display=="block"}invalidateCanvas(orig_image,mask_image){this.imgCanvas.width=orig_image.width,this.imgCanvas.height=orig_image.height,this.maskCanvas.width=orig_image.width,this.maskCanvas.height=orig_image.height;let imgCtx=this.imgCanvas.getContext("2d",{willReadFrequently:!0}),maskCtx=this.maskCanvas.getContext("2d",{willReadFrequently:!0});imgCtx.drawImage(orig_image,0,0,orig_image.width,orig_image.height),prepare_mask(mask_image,this.maskCanvas,maskCtx,this.getMaskColor())}setImages(imgCanvas){return __async(this,null,function*(){let self=this;const imgCtx=imgCanvas.getContext("2d",{willReadFrequently:!0}),maskCtx=this.maskCtx,maskCanvas=this.maskCanvas;imgCtx.clearRect(0,0,this.imgCanvas.width,this.imgCanvas.height),maskCtx.clearRect(0,0,this.maskCanvas.width,this.maskCanvas.height);const filepath=ComfyApp.clipspace.images,alpha_url=new URL(ComfyApp.clipspace.imgs[ComfyApp.clipspace.selectedIndex].src);alpha_url.searchParams.delete("channel"),alpha_url.searchParams.delete("preview"),alpha_url.searchParams.set("channel","a");let mask_image=yield loadImage(alpha_url);const rgb_url=new URL(ComfyApp.clipspace.imgs[ComfyApp.clipspace.selectedIndex].src);rgb_url.searchParams.delete("channel"),rgb_url.searchParams.set("channel","rgb"),this.image=new Image,this.image.onload=function(){maskCanvas.width=self.image.width,maskCanvas.height=self.image.height,self.invalidateCanvas(self.image,mask_image),self.initializeCanvasPanZoom()},this.image.src=rgb_url.toString()})}initializeCanvasPanZoom(){let drawWidth=this.image.width,drawHeight=this.image.height,width=this.element.clientWidth,height=this.element.clientHeight;this.image.width>width&&(drawWidth=width,drawHeight=drawWidth/this.image.width*this.image.height),drawHeight>height&&(drawHeight=height,drawWidth=drawHeight/this.image.height*this.image.width),this.zoom_ratio=drawWidth/this.image.width;const canvasX=(width-drawWidth)/2,canvasY=(height-drawHeight)/2;this.pan_x=canvasX,this.pan_y=canvasY,this.invalidatePanZoom()}invalidatePanZoom(){let raw_width=this.image.width*this.zoom_ratio,raw_height=this.image.height*this.zoom_ratio;this.pan_x+raw_width<10&&(this.pan_x=10-raw_width),this.pan_y+raw_height<10&&(this.pan_y=10-raw_height);let width=`${raw_width}px`,height=`${raw_height}px`,left=`${this.pan_x}px`,top=`${this.pan_y}px`;this.maskCanvas.style.width=width,this.maskCanvas.style.height=height,this.maskCanvas.style.left=left,this.maskCanvas.style.top=top,this.imgCanvas.style.width=width,this.imgCanvas.style.height=height,this.imgCanvas.style.left=left,this.imgCanvas.style.top=top}setEventHandler(maskCanvas){const self=this;this.handler_registered||(maskCanvas.addEventListener("contextmenu",event=>{event.preventDefault()}),this.element.addEventListener("wheel",event=>this.handleWheelEvent(self,event)),this.element.addEventListener("pointermove",event=>this.pointMoveEvent(self,event)),this.element.addEventListener("touchmove",event=>this.pointMoveEvent(self,event)),this.element.addEventListener("dragstart",event=>{event.ctrlKey&&event.preventDefault()}),maskCanvas.addEventListener("pointerdown",event=>this.handlePointerDown(self,event)),maskCanvas.addEventListener("pointermove",event=>this.draw_move(self,event)),maskCanvas.addEventListener("touchmove",event=>this.draw_move(self,event)),maskCanvas.addEventListener("pointerover",event=>{this.brush.style.display="block"}),maskCanvas.addEventListener("pointerleave",event=>{this.brush.style.display="none"}),document.addEventListener("pointerup",_MaskEditorDialog.handlePointerUp),this.handler_registered=!0)}getMaskCanvasStyle(){return this.brush_color_mode==="negative"?{mixBlendMode:"difference",opacity:"1"}:{mixBlendMode:"initial",opacity:this.brush_opacity}}getMaskColor(){return this.brush_color_mode==="black"?{r:0,g:0,b:0}:this.brush_color_mode==="white"?{r:255,g:255,b:255}:this.brush_color_mode==="negative"?{r:255,g:255,b:255}:{r:0,g:0,b:0}}getMaskFillStyle(){const maskColor=this.getMaskColor();return"rgb("+maskColor.r+","+maskColor.g+","+maskColor.b+")"}getColorButtonText(){let colorCaption="unknown";return this.brush_color_mode==="black"?colorCaption="black":this.brush_color_mode==="white"?colorCaption="white":this.brush_color_mode==="negative"&&(colorCaption="negative"),"Color: "+colorCaption}updateWhenBrushColorModeChanged(){this.colorButton.innerText=this.getColorButtonText();const maskCanvasStyle=this.getMaskCanvasStyle();this.maskCanvas.style.mixBlendMode=maskCanvasStyle.mixBlendMode,this.maskCanvas.style.opacity=maskCanvasStyle.opacity.toString();const maskColor=this.getMaskColor(),maskData=this.maskCtx.getImageData(0,0,this.maskCanvas.width,this.maskCanvas.height);for(let i=0;i20&&!this.drawing_mode?requestAnimationFrame(()=>{self.maskCtx.beginPath(),self.maskCtx.fillStyle=this.getMaskFillStyle(),self.maskCtx.globalCompositeOperation="source-over",self.maskCtx.arc(x,y,brush_size,0,Math.PI*2,!1),self.maskCtx.fill(),self.lastx=x,self.lasty=y}):requestAnimationFrame(()=>{self.maskCtx.beginPath(),self.maskCtx.fillStyle=this.getMaskFillStyle(),self.maskCtx.globalCompositeOperation="source-over";for(var dx=x-self.lastx,dy=y-self.lasty,distance=Math.sqrt(dx*dx+dy*dy),directionX=dx/distance,directionY=dy/distance,i=0;i20&&!this.drawing_mode?requestAnimationFrame(()=>{self.maskCtx.beginPath(),self.maskCtx.globalCompositeOperation="destination-out",self.maskCtx.arc(x2,y2,brush_size,0,Math.PI*2,!1),self.maskCtx.fill(),self.lastx=x2,self.lasty=y2}):requestAnimationFrame(()=>{self.maskCtx.beginPath(),self.maskCtx.globalCompositeOperation="destination-out";for(var dx=x2-self.lastx,dy=y2-self.lasty,distance=Math.sqrt(dx*dx+dy*dy),directionX=dx/distance,directionY=dy/distance,i=0;iobj.name==="image");index>=0&&(ComfyApp.clipspace.widgets[index].value=item)}const dataURL=backupCanvas.toDataURL(),blob=dataURLToBlob(dataURL);let original_url=new URL(this.image.src);const original_ref={filename:original_url.searchParams.get("filename")};let original_subfolder=original_url.searchParams.get("subfolder");original_subfolder&&(original_ref.subfolder=original_subfolder);let original_type=original_url.searchParams.get("type");original_type&&(original_ref.type=original_type),formData.append("image",blob,filename),formData.append("original_ref",JSON.stringify(original_ref)),formData.append("type","input"),formData.append("subfolder","clipspace"),this.saveButton.innerText="Saving...",this.saveButton.disabled=!0,yield uploadMask(item,formData),ComfyApp.onClipspaceEditorSave(),this.close()})}};__name(_MaskEditorDialog,"MaskEditorDialog"),__publicField(_MaskEditorDialog,"instance",null),__publicField(_MaskEditorDialog,"mousedown_x",null),__publicField(_MaskEditorDialog,"mousedown_y",null);let MaskEditorDialog=_MaskEditorDialog;app.registerExtension({name:"Comfy.MaskEditor",init(app2){ComfyApp.open_maskeditor=function(){const dlg=MaskEditorDialog.getInstance();dlg.isOpened()||dlg.show()};const context_predicate=__name(()=>ComfyApp.clipspace&&ComfyApp.clipspace.imgs&&ComfyApp.clipspace.imgs.length>0,"context_predicate");ClipspaceDialog.registerButton("MaskEditor",context_predicate,ComfyApp.open_maskeditor)}});const id="Comfy.NodeTemplates",file="comfy.templates.json",_ManageTemplates=class _ManageTemplates extends ComfyDialog{constructor(){super();__publicField(this,"templates");__publicField(this,"draggedEl");__publicField(this,"saveVisualCue");__publicField(this,"emptyImg");__publicField(this,"importInput");this.load().then(v=>{this.templates=v}),this.element.classList.add("comfy-manage-templates"),this.draggedEl=null,this.saveVisualCue=null,this.emptyImg=new Image,this.emptyImg.src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=",this.importInput=$el("input",{type:"file",accept:".json",multiple:!0,style:{display:"none"},parent:document.body,onchange:__name(()=>this.importAll(),"onchange")})}createButtons(){const btns=super.createButtons();return btns[0].textContent="Close",btns[0].onclick=e=>{clearTimeout(this.saveVisualCue),this.close()},btns.unshift($el("button",{type:"button",textContent:"Export",onclick:__name(()=>this.exportAll(),"onclick")})),btns.unshift($el("button",{type:"button",textContent:"Import",onclick:__name(()=>{this.importInput.click()},"onclick")})),btns}load(){return __async(this,null,function*(){let templates=[];if(app.storageLocation==="server")if(app.isNewUserSession){const json=localStorage.getItem(id);json&&(templates=JSON.parse(json)),yield api.storeUserData(file,json,{stringify:!1})}else{const res=yield api.getUserData(file);if(res.status===200)try{templates=yield res.json()}catch(error){}else res.status!==404&&console.error(res.status+" "+res.statusText)}else{const json=localStorage.getItem(id);json&&(templates=JSON.parse(json))}return templates!=null?templates:[]})}store(){return __async(this,null,function*(){if(app.storageLocation==="server"){const templates=JSON.stringify(this.templates,void 0,4);localStorage.setItem(id,templates);try{yield api.storeUserData(file,templates,{stringify:!1})}catch(error){console.error(error),alert(error.message)}}else localStorage.setItem(id,JSON.stringify(this.templates))})}importAll(){return __async(this,null,function*(){for(const file2 of this.importInput.files)if(file2.type==="application/json"||file2.name.endsWith(".json")){const reader=new FileReader;reader.onload=()=>__async(this,null,function*(){const importFile=JSON.parse(reader.result);if(importFile!=null&&importFile.templates){for(const template of importFile.templates)template!=null&&template.name&&(template!=null&&template.data)&&this.templates.push(template);yield this.store()}}),yield reader.readAsText(file2)}this.importInput.value=null,this.close()})}exportAll(){if(this.templates.length==0){alert("No templates to export.");return}const json=JSON.stringify({templates:this.templates},null,2),blob=new Blob([json],{type:"application/json"}),url=URL.createObjectURL(blob),a=$el("a",{href:url,download:"node_templates.json",style:{display:"none"},parent:document.body});a.click(),setTimeout(function(){a.remove(),window.URL.revokeObjectURL(url)},0)}show(){super.show($el("div",{},this.templates.flatMap((t,i)=>{let nameInput;return[$el("div",{dataset:{id:i.toString()},className:"templateManagerRow",style:{display:"grid",gridTemplateColumns:"1fr auto",border:"1px dashed transparent",gap:"5px",backgroundColor:"var(--comfy-menu-bg)"},ondragstart:__name(e=>{this.draggedEl=e.currentTarget,e.currentTarget.style.opacity="0.6",e.currentTarget.style.border="1px dashed yellow",e.dataTransfer.effectAllowed="move",e.dataTransfer.setDragImage(this.emptyImg,0,0)},"ondragstart"),ondragend:__name(e=>{e.target.style.opacity="1",e.currentTarget.style.border="1px dashed transparent",e.currentTarget.removeAttribute("draggable"),this.element.querySelectorAll(".templateManagerRow").forEach((el,i2)=>{var prev_i=Number.parseInt(el.dataset.id);el==this.draggedEl&&prev_i!=i2&&this.templates.splice(i2,0,this.templates.splice(prev_i,1)[0]),el.dataset.id=i2.toString()}),this.store()},"ondragend"),ondragover:__name(e=>{if(e.preventDefault(),e.currentTarget==this.draggedEl)return;let rect=e.currentTarget.getBoundingClientRect();e.clientY>rect.top+rect.height/2?e.currentTarget.parentNode.insertBefore(this.draggedEl,e.currentTarget.nextSibling):e.currentTarget.parentNode.insertBefore(this.draggedEl,e.currentTarget)},"ondragover")},[$el("label",{textContent:"Name: ",style:{cursor:"grab"},onmousedown:__name(e=>{e.target.localName=="label"&&(e.currentTarget.parentNode.draggable="true")},"onmousedown")},[$el("input",{value:t.name,dataset:{name:t.name},style:{transitionProperty:"background-color",transitionDuration:"0s"},onchange:__name(e=>{clearTimeout(this.saveVisualCue);var el=e.target,row=el.parentNode.parentNode;this.templates[row.dataset.id].name=el.value.trim()||"untitled",this.store(),el.style.backgroundColor="rgb(40, 95, 40)",el.style.transitionDuration="0s",this.saveVisualCue=setTimeout(function(){el.style.transitionDuration=".7s",el.style.backgroundColor="var(--comfy-input-bg)"},15)},"onchange"),onkeypress:__name(e=>{var el=e.target;clearTimeout(this.saveVisualCue),el.style.transitionDuration="0s",el.style.backgroundColor="var(--comfy-input-bg)"},"onkeypress"),$:__name(el=>nameInput=el,"$")})]),$el("div",{},[$el("button",{textContent:"Export",style:{fontSize:"12px",fontWeight:"normal"},onclick:__name(e=>{const json=JSON.stringify({templates:[t]},null,2),blob=new Blob([json],{type:"application/json"}),url=URL.createObjectURL(blob),a=$el("a",{href:url,download:(nameInput.value||t.name)+".json",style:{display:"none"},parent:document.body});a.click(),setTimeout(function(){a.remove(),window.URL.revokeObjectURL(url)},0)},"onclick")}),$el("button",{textContent:"Delete",style:{fontSize:"12px",color:"red",fontWeight:"normal"},onclick:__name(e=>{const item=e.target.parentNode.parentNode;item.parentNode.removeChild(item),this.templates.splice(item.dataset.id*1,1),this.store();var that=this;setTimeout(function(){that.element.querySelectorAll(".templateManagerRow").forEach((el,i2)=>{el.dataset.id=i2.toString()})},0)},"onclick")})])])]})))}};__name(_ManageTemplates,"ManageTemplates");let ManageTemplates=_ManageTemplates;app.registerExtension({name:id,setup(){const manage=new ManageTemplates,clipboardAction=__name(cb=>__async(this,null,function*(){const old=localStorage.getItem("litegrapheditor_clipboard");yield cb(),localStorage.setItem("litegrapheditor_clipboard",old)}),"clipboardAction"),orig=LGraphCanvas.prototype.getCanvasMenuOptions;LGraphCanvas.prototype.getCanvasMenuOptions=function(){const options=orig.apply(this,arguments);options.push(null),options.push({content:"Save Selected as Template",disabled:!Object.keys(app.canvas.selected_nodes||{}).length,callback:__name(()=>{const name=prompt("Enter name");name!=null&&name.trim()&&clipboardAction(()=>{app.canvas.copyToClipboard();let data=localStorage.getItem("litegrapheditor_clipboard");data=JSON.parse(data);const nodeIds=Object.keys(app.canvas.selected_nodes);for(let i=0;i({content:t.name,callback:__name(()=>{clipboardAction(()=>__async(this,null,function*(){const data=JSON.parse(t.data);yield GroupNodeConfig.registerFromWorkflow(data.groupNodes,{}),localStorage.setItem("litegrapheditor_clipboard",t.data),app.canvas.pasteFromClipboard()}))},"callback")}));return subItems.push(null,{content:"Manage",callback:__name(()=>manage.show(),"callback")}),options.push({content:"Node Templates",submenu:{options:subItems}}),options}}});app.registerExtension({name:"Comfy.NoteNode",registerCustomNodes(){const _NoteNode=class _NoteNode{constructor(){__publicField(this,"color",LGraphCanvas.node_colors.yellow.color);__publicField(this,"bgcolor",LGraphCanvas.node_colors.yellow.bgcolor);__publicField(this,"groupcolor",LGraphCanvas.node_colors.yellow.groupcolor);__publicField(this,"properties");__publicField(this,"serialize_widgets");__publicField(this,"isVirtualNode");__publicField(this,"collapsable");__publicField(this,"title_mode");this.properties||(this.properties={text:""}),ComfyWidgets.STRING(this,"",["",{default:this.properties.text,multiline:!0}],app),this.serialize_widgets=!0,this.isVirtualNode=!0}};__name(_NoteNode,"NoteNode"),__publicField(_NoteNode,"category");let NoteNode=_NoteNode;LiteGraph.registerNodeType("Note",Object.assign(NoteNode,{title_mode:LiteGraph.NORMAL_TITLE,title:"Note",collapsable:!0})),NoteNode.category="utils"}});app.registerExtension({name:"Comfy.RerouteNode",registerCustomNodes(app2){const _RerouteNode=class _RerouteNode{constructor(){this.properties||(this.properties={}),this.properties.showOutputText=_RerouteNode.defaultVisibility,this.properties.horizontal=!1,this.addInput("","*"),this.addOutput(this.properties.showOutputText?"*":"","*"),this.onAfterGraphConfigured=function(){requestAnimationFrame(()=>{this.onConnectionsChange(LiteGraph.INPUT,null,!0,null)})},this.onConnectionsChange=function(type,index,connected,link_info){var _a,_b,_c,_d,_e;if(this.applyOrientation(),connected&&type===LiteGraph.OUTPUT&&new Set(this.outputs[0].links.map(l=>app2.graph.links[l].type).filter(t=>t!=="*")).size>1){const linksToDisconnect=[];for(let i=0;iw.name===targetInput.widget.name));const merged=mergeIfValid(targetInput,[config[0],widgetConfig]);merged.customConfig&&(widgetConfig=merged.customConfig)}}}}for(const node of updateNodes)widgetConfig&&outputType?(node.inputs[0].widget={name:"value"},setWidgetConfig(node.inputs[0],[widgetType!=null?widgetType:displayType,widgetConfig],targetWidget)):setWidgetConfig(node.inputs[0],null);if(inputNode){const link=app2.graph.links[inputNode.inputs[0].link];link&&(link.color=color)}},this.clone=function(){const cloned=_RerouteNode.prototype.clone.apply(this);return cloned.removeOutput(0),cloned.addOutput(this.properties.showOutputText?"*":"","*"),cloned.size=cloned.computeSize(),cloned},this.isVirtualNode=!0}getExtraMenuOptions(_,options){options.unshift({content:(this.properties.showOutputText?"Hide":"Show")+" Type",callback:__name(()=>{this.properties.showOutputText=!this.properties.showOutputText,this.properties.showOutputText?this.outputs[0].name=this.__outputType||this.outputs[0].type:this.outputs[0].name="",this.size=this.computeSize(),this.applyOrientation(),app2.graph.setDirtyCanvas(!0,!0)},"callback")},{content:(_RerouteNode.defaultVisibility?"Hide":"Show")+" Type By Default",callback:__name(()=>{_RerouteNode.setDefaultTextVisibility(!_RerouteNode.defaultVisibility)},"callback")},{content:"Set "+(this.properties.horizontal?"Horizontal":"Vertical"),callback:__name(()=>{this.properties.horizontal=!this.properties.horizontal,this.applyOrientation()},"callback")})}applyOrientation(){this.horizontal=this.properties.horizontal,this.horizontal?this.inputs[0].pos=[this.size[0]/2,0]:delete this.inputs[0].pos,app2.graph.setDirtyCanvas(!0,!0)}computeSize(){return[this.properties.showOutputText&&this.outputs&&this.outputs.length?Math.max(75,LiteGraph.NODE_TEXT_SIZE*this.outputs[0].name.length*.6+40):75,26]}static setDefaultTextVisibility(visible){_RerouteNode.defaultVisibility=visible,visible?localStorage["Comfy.RerouteNode.DefaultVisibility"]="true":delete localStorage["Comfy.RerouteNode.DefaultVisibility"]}};__name(_RerouteNode,"RerouteNode"),__publicField(_RerouteNode,"category"),__publicField(_RerouteNode,"defaultVisibility",!1);let RerouteNode=_RerouteNode;RerouteNode.setDefaultTextVisibility(!!localStorage["Comfy.RerouteNode.DefaultVisibility"]),LiteGraph.registerNodeType("Reroute",Object.assign(RerouteNode,{title_mode:LiteGraph.NO_TITLE,title:"Reroute",collapsable:!1})),RerouteNode.category="utils"}});app.registerExtension({name:"Comfy.SaveImageExtraOutput",beforeRegisterNodeDef(nodeType,nodeData,app2){return __async(this,null,function*(){if(nodeData.name==="SaveImage"||nodeData.name==="SaveAnimatedWEBP"){const onNodeCreated=nodeType.prototype.onNodeCreated;nodeType.prototype.onNodeCreated=function(){const r=onNodeCreated?onNodeCreated.apply(this,arguments):void 0,widget=this.widgets.find(w=>w.name==="filename_prefix");return widget.serializeValue=()=>applyTextReplacements(app2,widget.value),r}}else{const onNodeCreated=nodeType.prototype.onNodeCreated;nodeType.prototype.onNodeCreated=function(){const r=onNodeCreated?onNodeCreated.apply(this,arguments):void 0;return(!this.properties||!("Node name for S&R"in this.properties))&&this.addProperty("Node name for S&R",this.constructor.type,"string"),r}}})}});let touchZooming,touchCount=0;app.registerExtension({name:"Comfy.SimpleTouchSupport",setup(){let zoomPos,touchTime,lastTouch;function getMultiTouchPos(e){return Math.hypot(e.touches[0].clientX-e.touches[1].clientX,e.touches[0].clientY-e.touches[1].clientY)}__name(getMultiTouchPos,"getMultiTouchPos"),app.canvasEl.addEventListener("touchstart",e=>{var _a,_b;touchCount++,lastTouch=null,((_a=e.touches)==null?void 0:_a.length)===1?(touchTime=new Date,lastTouch=e.touches[0]):(touchTime=null,((_b=e.touches)==null?void 0:_b.length)===2&&(zoomPos=getMultiTouchPos(e),app.canvas.pointer_is_down=!1))},!0),app.canvasEl.addEventListener("touchend",e=>{var _a,_b,_c;if(touchZooming=!1,touchCount=(_b=(_a=e.touches)==null?void 0:_a.length)!=null?_b:touchCount-1,touchTime&&!((_c=e.touches)!=null&&_c.length)){if(new Date().getTime()-touchTime>600){try{e.constructor=CustomEvent}catch(error){}e.clientX=lastTouch.clientX,e.clientY=lastTouch.clientY,app.canvas.pointer_is_down=!0,app.canvas._mousedown_callback(e)}touchTime=null}}),app.canvasEl.addEventListener("touchmove",e=>{var _a,_b;if(touchTime=null,((_a=e.touches)==null?void 0:_a.length)===2){app.canvas.pointer_is_down=!1,touchZooming=!0,LiteGraph.closeAllContextMenus(),(_b=app.canvas.search_box)==null||_b.close();const newZoomPos=getMultiTouchPos(e),midX=(e.touches[0].clientX+e.touches[1].clientX)/2,midY=(e.touches[0].clientY+e.touches[1].clientY)/2;let scale=app.canvas.ds.scale;const diff=zoomPos-newZoomPos;diff>.5?scale*=1/1.07:diff<-.5&&(scale*=1.07),app.canvas.ds.changeScale(scale,[midX,midY]),app.canvas.setDirty(!0,!0),zoomPos=newZoomPos}},!0)}});const processMouseDown=LGraphCanvas.prototype.processMouseDown;LGraphCanvas.prototype.processMouseDown=function(e){if(!(touchZooming||touchCount))return processMouseDown.apply(this,arguments)};const processMouseMove=LGraphCanvas.prototype.processMouseMove;LGraphCanvas.prototype.processMouseMove=function(e){if(!(touchZooming||touchCount>1))return processMouseMove.apply(this,arguments)};app.registerExtension({name:"Comfy.SlotDefaults",suggestionsNumber:null,init(){LiteGraph.search_filter_enabled=!0,LiteGraph.middle_click_slot_add_default_node=!0,this.suggestionsNumber=app.ui.settings.addSetting({id:"Comfy.NodeSuggestions.number",name:"Number of nodes suggestions",type:"slider",attrs:{min:1,max:100,step:1},defaultValue:5,onChange:__name((newVal,oldVal)=>{this.setDefaults(newVal)},"onChange")})},slot_types_default_out:{},slot_types_default_in:{},beforeRegisterNodeDef(nodeType,nodeData,app2){return __async(this,null,function*(){var nodeId=nodeData.name,inputs=[];inputs=nodeData.input.required;for(const inputKey in inputs){var input=inputs[inputKey];if(typeof input[0]!="string")continue;var type=input[0];if(type in ComfyWidgets){var customProperties=input[1];if(!(customProperties!=null&&customProperties.forceInput))continue}if(type in this.slot_types_default_out||(this.slot_types_default_out[type]=["Reroute"]),this.slot_types_default_out[type].includes(nodeId))continue;this.slot_types_default_out[type].push(nodeId);const lowerType=type.toLocaleLowerCase();lowerType in LiteGraph.registered_slot_in_types||(LiteGraph.registered_slot_in_types[lowerType]={nodes:[]}),LiteGraph.registered_slot_in_types[lowerType].nodes.push(nodeType.comfyClass)}var outputs=nodeData.output;for(const key in outputs){var type=outputs[key];type in this.slot_types_default_in||(this.slot_types_default_in[type]=["Reroute"]),this.slot_types_default_in[type].push(nodeId),type in LiteGraph.registered_slot_out_types||(LiteGraph.registered_slot_out_types[type]={nodes:[]}),LiteGraph.registered_slot_out_types[type].nodes.push(nodeType.comfyClass),LiteGraph.slot_types_out.includes(type)||LiteGraph.slot_types_out.push(type)}var maxNum=this.suggestionsNumber.value;this.setDefaults(maxNum)})},setDefaults(maxNum){LiteGraph.slot_types_default_out={},LiteGraph.slot_types_default_in={};for(const type in this.slot_types_default_out)LiteGraph.slot_types_default_out[type]=this.slot_types_default_out[type].slice(0,maxNum);for(const type in this.slot_types_default_in)LiteGraph.slot_types_default_in[type]=this.slot_types_default_in[type].slice(0,maxNum)}});function roundVectorToGrid(vec){return vec[0]=LiteGraph.CANVAS_GRID_SIZE*Math.round(vec[0]/LiteGraph.CANVAS_GRID_SIZE),vec[1]=LiteGraph.CANVAS_GRID_SIZE*Math.round(vec[1]/LiteGraph.CANVAS_GRID_SIZE),vec}__name(roundVectorToGrid,"roundVectorToGrid");app.registerExtension({name:"Comfy.SnapToGrid",init(){app.ui.settings.addSetting({id:"Comfy.SnapToGrid.GridSize",name:"Grid Size",type:"slider",attrs:{min:1,max:500},tooltip:"When dragging and resizing nodes while holding shift they will be aligned to the grid, this controls the size of that grid.",defaultValue:LiteGraph.CANVAS_GRID_SIZE,onChange(value){LiteGraph.CANVAS_GRID_SIZE=+value}});const onNodeMoved=app.canvas.onNodeMoved;app.canvas.onNodeMoved=function(node){const r=onNodeMoved==null?void 0:onNodeMoved.apply(this,arguments);if(app.shiftDown)for(const id2 in this.selected_nodes)this.selected_nodes[id2].alignToGrid();return r};const onNodeAdded=app.graph.onNodeAdded;app.graph.onNodeAdded=function(node){const onResize=node.onResize;return node.onResize=function(){return app.shiftDown&&roundVectorToGrid(node.size),onResize==null?void 0:onResize.apply(this,arguments)},onNodeAdded==null?void 0:onNodeAdded.apply(this,arguments)};const origDrawNode=LGraphCanvas.prototype.drawNode;LGraphCanvas.prototype.drawNode=function(node,ctx){if(app.shiftDown&&this.node_dragged&&node.id in this.selected_nodes){const[x,y]=roundVectorToGrid([...node.pos]),shiftX=x-node.pos[0];let shiftY=y-node.pos[1],w,h;if(node.flags.collapsed)w=node._collapsed_width,h=LiteGraph.NODE_TITLE_HEIGHT,shiftY-=LiteGraph.NODE_TITLE_HEIGHT;else{w=node.size[0],h=node.size[1];let titleMode=node.constructor.title_mode;titleMode!==LiteGraph.TRANSPARENT_TITLE&&titleMode!==LiteGraph.NO_TITLE&&(h+=LiteGraph.NODE_TITLE_HEIGHT,shiftY-=LiteGraph.NODE_TITLE_HEIGHT)}const f=ctx.fillStyle;ctx.fillStyle="rgba(100, 100, 100, 0.5)",ctx.fillRect(shiftX,shiftY,w,h),ctx.fillStyle=f}return origDrawNode.apply(this,arguments)};let selectedAndMovingGroup=null;const groupMove=LGraphGroup.prototype.move;LGraphGroup.prototype.move=function(deltax,deltay,ignore_nodes){const v=groupMove.apply(this,arguments);if(!selectedAndMovingGroup&&app.canvas.selected_group===this&&(deltax||deltay)&&(selectedAndMovingGroup=this),app.canvas.last_mouse_dragging===!1&&app.shiftDown){this.recomputeInsideNodes();for(const node of this._nodes)node.alignToGrid();LGraphNode.prototype.alignToGrid.apply(this)}return v};const drawGroups=LGraphCanvas.prototype.drawGroups;LGraphCanvas.prototype.drawGroups=function(canvas,ctx){if(this.selected_group&&app.shiftDown){if(this.selected_group_resizing)roundVectorToGrid(this.selected_group.size);else if(selectedAndMovingGroup){const[x,y]=roundVectorToGrid([...selectedAndMovingGroup.pos]),f=ctx.fillStyle,s=ctx.strokeStyle;ctx.fillStyle="rgba(100, 100, 100, 0.33)",ctx.strokeStyle="rgba(100, 100, 100, 0.66)",ctx.rect(x,y,...selectedAndMovingGroup.size),ctx.fill(),ctx.stroke(),ctx.fillStyle=f,ctx.strokeStyle=s}}else this.selected_group||(selectedAndMovingGroup=null);return drawGroups.apply(this,arguments)};const onGroupAdd=LGraphCanvas.onGroupAdd;LGraphCanvas.onGroupAdd=function(){const v=onGroupAdd.apply(app.canvas,arguments);if(app.shiftDown){const lastGroup=app.graph._groups[app.graph._groups.length-1];lastGroup&&(roundVectorToGrid(lastGroup.pos),roundVectorToGrid(lastGroup.size))}return v}}});app.registerExtension({name:"Comfy.UploadImage",beforeRegisterNodeDef(nodeType,nodeData,app2){return __async(this,null,function*(){var _a,_b,_c,_d;((_d=(_c=(_b=(_a=nodeData==null?void 0:nodeData.input)==null?void 0:_a.required)==null?void 0:_b.image)==null?void 0:_c[1])==null?void 0:_d.image_upload)===!0&&(nodeData.input.required.upload=["IMAGEUPLOAD"])})}});const WEBCAM_READY=Symbol();app.registerExtension({name:"Comfy.WebcamCapture",getCustomWidgets(app2){return{WEBCAM(node,inputName){let res;node[WEBCAM_READY]=new Promise(resolve=>res=resolve);const container=document.createElement("div");container.style.background="rgba(0,0,0,0.25)",container.style.textAlign="center";const video=document.createElement("video");return video.style.height=video.style.width="100%",__name(()=>__async(this,null,function*(){try{const stream=yield navigator.mediaDevices.getUserMedia({video:!0,audio:!1});container.replaceChildren(video),setTimeout(()=>res(video),500),video.addEventListener("loadedmetadata",()=>res(video),!1),video.srcObject=stream,video.play()}catch(error){const label=document.createElement("div");label.style.color="red",label.style.overflow="auto",label.style.maxHeight="100%",label.style.whiteSpace="pre-wrap",window.isSecureContext?label.textContent=`Unable to load webcam, please ensure access is granted: `+error.message:label.textContent=`Unable to load webcam. A secure context is required, if you are not accessing ComfyUI on localhost (127.0.0.1) you will have to enable TLS (https) `+error.message,container.replaceChildren(label)}}),"loadVideo")(),{widget:node.addDOMWidget(inputName,"WEBCAM",container)}}}},nodeCreated(node){if(node.type,node.constructor.comfyClass!=="WebcamCapture")return;let video;const camera=node.widgets.find(w2=>w2.name==="image"),w=node.widgets.find(w2=>w2.name==="width"),h=node.widgets.find(w2=>w2.name==="height"),captureOnQueue=node.widgets.find(w2=>w2.name==="capture_on_queue"),canvas=document.createElement("canvas"),capture=__name(()=>{canvas.width=w.value,canvas.height=h.value,canvas.getContext("2d").drawImage(video,0,0,w.value,h.value);const data=canvas.toDataURL("image/png"),img=new Image;img.onload=()=>{node.imgs=[img],app.graph.setDirtyCanvas(!0),requestAnimationFrame(()=>{var _a;(_a=node.setSizeForImage)==null||_a.call(node)})},img.src=data},"capture"),btn=node.addWidget("button","waiting for camera...","capture",capture);btn.disabled=!0,btn.serializeValue=()=>{},camera.serializeValue=()=>__async(this,null,function*(){var _a;if(captureOnQueue.value)capture();else if(!((_a=node.imgs)!=null&&_a.length)){const err="No webcam image captured";throw alert(err),new Error(err)}const blob=yield new Promise(r=>canvas.toBlob(r)),name=`${+new Date}.png`,file2=new File([blob],name),body=new FormData;body.append("image",file2),body.append("subfolder","webcam"),body.append("type","temp");const resp=yield api.fetchApi("/upload/image",{method:"POST",body});if(resp.status!==200){const err=`Error uploading camera image: ${resp.status} - ${resp.statusText}`;throw alert(err),new Error(err)}return`webcam/${name} [temp]`}),node[WEBCAM_READY].then(v=>{video=v,w.value||(w.value=video.videoWidth||640,h.value=video.videoHeight||480),btn.disabled=!1,btn.label="capture"})}});function splitFilePath(path){const folder_separator=path.lastIndexOf("/");return folder_separator===-1?["",path]:[path.substring(0,folder_separator),path.substring(folder_separator+1)]}__name(splitFilePath,"splitFilePath");function getResourceURL(subfolder,filename,type="input"){return`/view?${["filename="+encodeURIComponent(filename),"type="+type,"subfolder="+subfolder,app.getRandParam().substring(1)].join("&")}`}__name(getResourceURL,"getResourceURL");function uploadFile(audioWidget,audioUIWidget,file2,updateNode,pasted=!1){return __async(this,null,function*(){try{const body=new FormData;body.append("image",file2),pasted&&body.append("subfolder","pasted");const resp=yield api.fetchApi("/upload/image",{method:"POST",body});if(resp.status===200){const data=yield resp.json();let path=data.name;data.subfolder&&(path=data.subfolder+"/"+path),audioWidget.options.values.includes(path)||audioWidget.options.values.push(path),updateNode&&(audioUIWidget.element.src=api.apiURL(getResourceURL(...splitFilePath(path))),audioWidget.value=path)}else alert(resp.status+" - "+resp.statusText)}catch(error){alert(error)}})}__name(uploadFile,"uploadFile");app.registerExtension({name:"Comfy.AudioWidget",beforeRegisterNodeDef(nodeType,nodeData){return __async(this,null,function*(){["LoadAudio","SaveAudio","PreviewAudio"].includes(nodeType.comfyClass)&&(nodeData.input.required.audioUI=["AUDIO_UI"])})},getCustomWidgets(){return{AUDIO_UI(node,inputName){const audio=document.createElement("audio");audio.controls=!0,audio.classList.add("comfy-audio"),audio.setAttribute("name","media");const audioUIWidget=node.addDOMWidget(inputName,"audioUI",audio);if(audioUIWidget.serialize=!1,node.constructor.nodeData.output_node){audioUIWidget.element.classList.add("empty-audio-widget");const onExecuted=node.onExecuted;node.onExecuted=function(message){onExecuted==null||onExecuted.apply(this,arguments);const audios=message.audio;if(!audios)return;const audio2=audios[0];audioUIWidget.element.src=api.apiURL(getResourceURL(audio2.subfolder,audio2.filename,audio2.type)),audioUIWidget.element.classList.remove("empty-audio-widget")}}return{widget:audioUIWidget}}}},onNodeOutputsUpdated(nodeOutputs){for(const[nodeId,output]of Object.entries(nodeOutputs)){const node=app.graph.getNodeById(Number.parseInt(nodeId));if("audio"in output){const audioUIWidget=node.widgets.find(w=>w.name==="audioUI"),audio=output.audio[0];audioUIWidget.element.src=api.apiURL(getResourceURL(audio.subfolder,audio.filename,audio.type)),audioUIWidget.element.classList.remove("empty-audio-widget")}}}});app.registerExtension({name:"Comfy.UploadAudio",beforeRegisterNodeDef(nodeType,nodeData){return __async(this,null,function*(){var _a,_b,_c,_d;((_d=(_c=(_b=(_a=nodeData==null?void 0:nodeData.input)==null?void 0:_a.required)==null?void 0:_b.audio)==null?void 0:_c[1])==null?void 0:_d.audio_upload)===!0&&(nodeData.input.required.upload=["AUDIOUPLOAD"])})},getCustomWidgets(){return{AUDIOUPLOAD(node,inputName){const audioWidget=node.widgets.find(w=>w.name==="audio"),audioUIWidget=node.widgets.find(w=>w.name==="audioUI"),onAudioWidgetUpdate=__name(()=>{audioUIWidget.element.src=api.apiURL(getResourceURL(...splitFilePath(audioWidget.value)))},"onAudioWidgetUpdate");audioWidget.value&&onAudioWidgetUpdate(),audioWidget.callback=onAudioWidgetUpdate;const onGraphConfigured=node.onGraphConfigured;node.onGraphConfigured=function(){onGraphConfigured==null||onGraphConfigured.apply(this,arguments),audioWidget.value&&onAudioWidgetUpdate()};const fileInput=document.createElement("input");fileInput.type="file",fileInput.accept="audio/*",fileInput.style.display="none",fileInput.onchange=()=>{fileInput.files.length&&uploadFile(audioWidget,audioUIWidget,fileInput.files[0],!0)};const uploadWidget=node.addWidget("button",inputName,"",()=>{fileInput.click()});return uploadWidget.label="choose file to upload",uploadWidget.serialize=!1,{widget:uploadWidget}}}}}); //# sourceMappingURL=index-Bln5LBF6.js.map