comfyui-frontend-package 1.38.5__py3-none-any.whl → 1.38.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- comfyui_frontend_package/static/assets/{AboutPanel-CHse5rOA.js → AboutPanel-lkjGFasi.js} +2 -2
- comfyui_frontend_package/static/assets/{AboutPanel-CHse5rOA.js.map → AboutPanel-lkjGFasi.js.map} +1 -1
- comfyui_frontend_package/static/assets/{AudioPreviewPlayer-CAa8V66L.js → AudioPreviewPlayer-BxCSKPl9.js} +2 -2
- comfyui_frontend_package/static/assets/{AudioPreviewPlayer-CAa8V66L.js.map → AudioPreviewPlayer-BxCSKPl9.js.map} +1 -1
- comfyui_frontend_package/static/assets/AudioPreviewPlayer-CkxKvcVf.js +1 -0
- comfyui_frontend_package/static/assets/{BaseViewTemplate-DA6zfigT.js → BaseViewTemplate-CjODF2hh.js} +2 -2
- comfyui_frontend_package/static/assets/{BaseViewTemplate-DA6zfigT.js.map → BaseViewTemplate-CjODF2hh.js.map} +1 -1
- comfyui_frontend_package/static/assets/{CloudAuthTimeoutView-9OPBS1hE.js → CloudAuthTimeoutView-D-QkjPNh.js} +2 -2
- comfyui_frontend_package/static/assets/{CloudAuthTimeoutView-9OPBS1hE.js.map → CloudAuthTimeoutView-D-QkjPNh.js.map} +1 -1
- comfyui_frontend_package/static/assets/{CloudBadge-BnLiAHDN.js → CloudBadge-B4nmLus2.js} +2 -2
- comfyui_frontend_package/static/assets/{CloudBadge-BnLiAHDN.js.map → CloudBadge-B4nmLus2.js.map} +1 -1
- comfyui_frontend_package/static/assets/{CloudForgotPasswordView-BqDR_C7K.js → CloudForgotPasswordView-DOEV9hGr.js} +2 -2
- comfyui_frontend_package/static/assets/{CloudForgotPasswordView-BqDR_C7K.js.map → CloudForgotPasswordView-DOEV9hGr.js.map} +1 -1
- comfyui_frontend_package/static/assets/{CloudLayoutView-vTrrVUOY.js → CloudLayoutView-ShKH6rRV.js} +2 -2
- comfyui_frontend_package/static/assets/{CloudLayoutView-vTrrVUOY.js.map → CloudLayoutView-ShKH6rRV.js.map} +1 -1
- comfyui_frontend_package/static/assets/{CloudLoginView-T17euJly.js → CloudLoginView-C3Te42U9.js} +2 -2
- comfyui_frontend_package/static/assets/{CloudLoginView-T17euJly.js.map → CloudLoginView-C3Te42U9.js.map} +1 -1
- comfyui_frontend_package/static/assets/CloudRunButtonWrapper-Cub7EB34.js +3 -0
- comfyui_frontend_package/static/assets/{CloudRunButtonWrapper-hQc4BNkX.js.map → CloudRunButtonWrapper-Cub7EB34.js.map} +1 -1
- comfyui_frontend_package/static/assets/{CloudSignupView-vEDby5k3.js → CloudSignupView-X2oiL3ZR.js} +2 -2
- comfyui_frontend_package/static/assets/{CloudSignupView-vEDby5k3.js.map → CloudSignupView-X2oiL3ZR.js.map} +1 -1
- comfyui_frontend_package/static/assets/{CloudSubscriptionRedirectView-DPyO745g.js → CloudSubscriptionRedirectView-UjNv8emo.js} +2 -2
- comfyui_frontend_package/static/assets/{CloudSubscriptionRedirectView-DPyO745g.js.map → CloudSubscriptionRedirectView-UjNv8emo.js.map} +1 -1
- comfyui_frontend_package/static/assets/{CloudSurveyView-CBtTd9Ru.js → CloudSurveyView-IaiucCTP.js} +2 -2
- comfyui_frontend_package/static/assets/{CloudSurveyView-CBtTd9Ru.js.map → CloudSurveyView-IaiucCTP.js.map} +1 -1
- comfyui_frontend_package/static/assets/ComfyQueueButton-BppnHbrl.js +1 -0
- comfyui_frontend_package/static/assets/{ComfyQueueButton-MZrp7wYJ.js → ComfyQueueButton-HjSIKZKO.js} +2 -2
- comfyui_frontend_package/static/assets/{ComfyQueueButton-MZrp7wYJ.js.map → ComfyQueueButton-HjSIKZKO.js.map} +1 -1
- comfyui_frontend_package/static/assets/{ExtensionPanel-CrWVGUtg.js → ExtensionPanel-Bzb9QtKj.js} +2 -2
- comfyui_frontend_package/static/assets/{ExtensionPanel-CrWVGUtg.js.map → ExtensionPanel-Bzb9QtKj.js.map} +1 -1
- comfyui_frontend_package/static/assets/{GlobalToast-BiCmpIvO.js → GlobalToast-BSCvu6Hw.js} +2 -2
- comfyui_frontend_package/static/assets/{GlobalToast-BiCmpIvO.js.map → GlobalToast-BSCvu6Hw.js.map} +1 -1
- comfyui_frontend_package/static/assets/{GraphView-BCkpNGgz.js → GraphView-gYVCtm1V.js} +5 -5
- comfyui_frontend_package/static/assets/GraphView-gYVCtm1V.js.map +1 -0
- comfyui_frontend_package/static/assets/{KeybindingPanel-CAXL5TlV.js → KeybindingPanel-DF-bG4iO.js} +2 -2
- comfyui_frontend_package/static/assets/{KeybindingPanel-CAXL5TlV.js.map → KeybindingPanel-DF-bG4iO.js.map} +1 -1
- comfyui_frontend_package/static/assets/{LegacyCreditsPanel-6vR8koQy.js → LegacyCreditsPanel-D-CboO8k.js} +2 -2
- comfyui_frontend_package/static/assets/{LegacyCreditsPanel-6vR8koQy.js.map → LegacyCreditsPanel-D-CboO8k.js.map} +1 -1
- comfyui_frontend_package/static/assets/Load3D-c9UwgGoI.js +1 -0
- comfyui_frontend_package/static/assets/{Load3D-ei1BUF9O.js → Load3D-vYr8M3jJ.js} +2 -2
- comfyui_frontend_package/static/assets/{Load3D-ei1BUF9O.js.map → Load3D-vYr8M3jJ.js.map} +1 -1
- comfyui_frontend_package/static/assets/{PanelTemplate-BjN5XNg2.js → PanelTemplate-BJda9e5J.js} +2 -2
- comfyui_frontend_package/static/assets/{PanelTemplate-BjN5XNg2.js.map → PanelTemplate-BJda9e5J.js.map} +1 -1
- comfyui_frontend_package/static/assets/{ServerConfigPanel-CxovH9Qk.js → ServerConfigPanel-VsC6xlZJ.js} +2 -2
- comfyui_frontend_package/static/assets/{ServerConfigPanel-CxovH9Qk.js.map → ServerConfigPanel-VsC6xlZJ.js.map} +1 -1
- comfyui_frontend_package/static/assets/{SubscribeButton-CTOQRkfg.js → SubscribeButton-DZBycfCA.js} +2 -2
- comfyui_frontend_package/static/assets/{SubscribeButton-CTOQRkfg.js.map → SubscribeButton-DZBycfCA.js.map} +1 -1
- comfyui_frontend_package/static/assets/{SubscribeToRun-DnXzV8y0.js → SubscribeToRun-4YolxBOL.js} +2 -2
- comfyui_frontend_package/static/assets/{SubscribeToRun-DnXzV8y0.js.map → SubscribeToRun-4YolxBOL.js.map} +1 -1
- comfyui_frontend_package/static/assets/{SubscriptionPanel-D9uv7z8f.js → SubscriptionPanel-B6txX4Vm.js} +2 -2
- comfyui_frontend_package/static/assets/{SubscriptionPanel-D9uv7z8f.js.map → SubscriptionPanel-B6txX4Vm.js.map} +1 -1
- comfyui_frontend_package/static/assets/{SubscriptionRequiredDialogContent--VmT16oc.js → SubscriptionRequiredDialogContent-COEF2VQ_.js} +2 -2
- comfyui_frontend_package/static/assets/{SubscriptionRequiredDialogContent--VmT16oc.js.map → SubscriptionRequiredDialogContent-COEF2VQ_.js.map} +1 -1
- comfyui_frontend_package/static/assets/{UserCheckView-spD3LyMu.js → UserCheckView-x-fkcYzc.js} +2 -2
- comfyui_frontend_package/static/assets/{UserCheckView-spD3LyMu.js.map → UserCheckView-x-fkcYzc.js.map} +1 -1
- comfyui_frontend_package/static/assets/{UserPanel-Su6NtJ5q.js → UserPanel-7N9QknQj.js} +2 -2
- comfyui_frontend_package/static/assets/{UserPanel-Su6NtJ5q.js.map → UserPanel-7N9QknQj.js.map} +1 -1
- comfyui_frontend_package/static/assets/{UserSelectView-C5LBOPcv.js → UserSelectView-BYjOkfSa.js} +2 -2
- comfyui_frontend_package/static/assets/{UserSelectView-C5LBOPcv.js.map → UserSelectView-BYjOkfSa.js.map} +1 -1
- comfyui_frontend_package/static/assets/{ValueControlPopover-BdlDzT8l.js → ValueControlPopover-BPAa35QG.js} +2 -2
- comfyui_frontend_package/static/assets/{ValueControlPopover-BdlDzT8l.js.map → ValueControlPopover-BPAa35QG.js.map} +1 -1
- comfyui_frontend_package/static/assets/{WidgetAudioUI-BDZxDx_r.js → WidgetAudioUI-Dw-r3Ews.js} +2 -2
- comfyui_frontend_package/static/assets/{WidgetAudioUI-BDZxDx_r.js.map → WidgetAudioUI-Dw-r3Ews.js.map} +1 -1
- comfyui_frontend_package/static/assets/{WidgetImageCrop-CYRW7t2Q.js → WidgetImageCrop-kERy9g5I.js} +2 -2
- comfyui_frontend_package/static/assets/{WidgetImageCrop-CYRW7t2Q.js.map → WidgetImageCrop-kERy9g5I.js.map} +1 -1
- comfyui_frontend_package/static/assets/{WidgetInputNumber-BOKO36G3.js → WidgetInputNumber-BaClCNAC.js} +1 -1
- comfyui_frontend_package/static/assets/WidgetInputNumber-DU_D0Fzy.js +3 -0
- comfyui_frontend_package/static/assets/WidgetInputNumber-DU_D0Fzy.js.map +1 -0
- comfyui_frontend_package/static/assets/{WidgetLegacy-Bslv9wZZ.js → WidgetLegacy-B4nipUM9.js} +1 -1
- comfyui_frontend_package/static/assets/{WidgetRecordAudio-Bzy8PIzN.js → WidgetRecordAudio-Nk8dH238.js} +2 -2
- comfyui_frontend_package/static/assets/{WidgetRecordAudio-Bzy8PIzN.js.map → WidgetRecordAudio-Nk8dH238.js.map} +1 -1
- comfyui_frontend_package/static/assets/WidgetSelect-DzZPpO_-.js +1 -0
- comfyui_frontend_package/static/assets/{WidgetSelect-zgrFVzHH.js → WidgetSelect-nSQrk_hd.js} +2 -2
- comfyui_frontend_package/static/assets/{WidgetSelect-zgrFVzHH.js.map → WidgetSelect-nSQrk_hd.js.map} +1 -1
- comfyui_frontend_package/static/assets/{WidgetWithControl-Dh2FWOiA.js → WidgetWithControl-Da6zUB5e.js} +3 -3
- comfyui_frontend_package/static/assets/{WidgetWithControl-Dh2FWOiA.js.map → WidgetWithControl-Da6zUB5e.js.map} +1 -1
- comfyui_frontend_package/static/assets/{api-CUAc7rDA.js → api-Dwq2LQIW.js} +4 -4
- comfyui_frontend_package/static/assets/api-Dwq2LQIW.js.map +1 -0
- comfyui_frontend_package/static/assets/{audioService-DvndbCi2.js → audioService-DvVaKhuU.js} +2 -2
- comfyui_frontend_package/static/assets/{audioService-DvndbCi2.js.map → audioService-DvVaKhuU.js.map} +1 -1
- comfyui_frontend_package/static/assets/{audioUtils-DpjpcKbH.js → audioUtils-DD4rUYVZ.js} +2 -2
- comfyui_frontend_package/static/assets/{audioUtils-DpjpcKbH.js.map → audioUtils-DD4rUYVZ.js.map} +1 -1
- comfyui_frontend_package/static/assets/{auth-B8ZZ0KKQ.js → auth-B9axG-yZ.js} +2 -2
- comfyui_frontend_package/static/assets/{auth-B8ZZ0KKQ.js.map → auth-B9axG-yZ.js.map} +1 -1
- comfyui_frontend_package/static/assets/auth-D74DTev8.js +1 -0
- comfyui_frontend_package/static/assets/{cloudBadges-C1a7fBky.js → cloudBadges-D5mGJbRy.js} +2 -2
- comfyui_frontend_package/static/assets/{cloudBadges-C1a7fBky.js.map → cloudBadges-D5mGJbRy.js.map} +1 -1
- comfyui_frontend_package/static/assets/{cloudFeedbackTopbarButton-DR0T8sWG.js → cloudFeedbackTopbarButton-RZUssOmb.js} +2 -2
- comfyui_frontend_package/static/assets/{cloudFeedbackTopbarButton-DR0T8sWG.js.map → cloudFeedbackTopbarButton-RZUssOmb.js.map} +1 -1
- comfyui_frontend_package/static/assets/{cloudRemoteConfig-DhMjC5TB.js → cloudRemoteConfig-F9J0iGyF.js} +2 -2
- comfyui_frontend_package/static/assets/{cloudRemoteConfig-DhMjC5TB.js.map → cloudRemoteConfig-F9J0iGyF.js.map} +1 -1
- comfyui_frontend_package/static/assets/{cloudSessionCookie-Duxk6ux1.js → cloudSessionCookie-MEORlqtg.js} +2 -2
- comfyui_frontend_package/static/assets/{cloudSessionCookie-Duxk6ux1.js.map → cloudSessionCookie-MEORlqtg.js.map} +1 -1
- comfyui_frontend_package/static/assets/{cloudSubscription-B8l6B9Nx.js → cloudSubscription-CuWNXKVx.js} +2 -2
- comfyui_frontend_package/static/assets/{cloudSubscription-B8l6B9Nx.js.map → cloudSubscription-CuWNXKVx.js.map} +1 -1
- comfyui_frontend_package/static/assets/{core-DBfeqMDR.js → core-IYu8XAIx.js} +4 -4
- comfyui_frontend_package/static/assets/{core-DBfeqMDR.js.map → core-IYu8XAIx.js.map} +1 -1
- comfyui_frontend_package/static/assets/{dialogService-BZ1FmjZL.js → dialogService-YG0RH337.js} +9 -9
- comfyui_frontend_package/static/assets/{dialogService-BZ1FmjZL.js.map → dialogService-YG0RH337.js.map} +1 -1
- comfyui_frontend_package/static/assets/firebaseAuthStore-DnNaPbuZ.js +1 -0
- comfyui_frontend_package/static/assets/{graphHasMissingNodes-C79Wi51S.js → graphHasMissingNodes-BhD1N6zI.js} +2 -2
- comfyui_frontend_package/static/assets/{graphHasMissingNodes-C79Wi51S.js.map → graphHasMissingNodes-BhD1N6zI.js.map} +1 -1
- comfyui_frontend_package/static/assets/{index-CGxJFSof.js → index-BMy3twho.js} +3 -3
- comfyui_frontend_package/static/assets/{index-CGxJFSof.js.map → index-BMy3twho.js.map} +1 -1
- comfyui_frontend_package/static/assets/{index-DNpOhRra.css → index-KMO9qFHH.css} +1 -1
- comfyui_frontend_package/static/assets/{keybindingService-B88NjeAU.js → keybindingService-CBLPjYHI.js} +2 -2
- comfyui_frontend_package/static/assets/{keybindingService-B88NjeAU.js.map → keybindingService-CBLPjYHI.js.map} +1 -1
- comfyui_frontend_package/static/assets/{releaseStore-x0vHjxrw.js → releaseStore-DDOxzkVb.js} +2 -2
- comfyui_frontend_package/static/assets/{releaseStore-x0vHjxrw.js.map → releaseStore-DDOxzkVb.js.map} +1 -1
- comfyui_frontend_package/static/assets/releaseStore-iVkqunL8.js +1 -0
- comfyui_frontend_package/static/assets/{subscriptionCheckoutUtil-B_OvUP2T.js → subscriptionCheckoutUtil-DswSOreM.js} +2 -2
- comfyui_frontend_package/static/assets/{subscriptionCheckoutUtil-B_OvUP2T.js.map → subscriptionCheckoutUtil-DswSOreM.js.map} +1 -1
- comfyui_frontend_package/static/assets/{useCurrentUser-BJcn2Vgo.js → useCurrentUser-NdaCJzIK.js} +1 -1
- comfyui_frontend_package/static/assets/{useErrorHandling-CI8_F4yx.js → useErrorHandling-Cfa5N_7c.js} +2 -2
- comfyui_frontend_package/static/assets/{useErrorHandling-CI8_F4yx.js.map → useErrorHandling-Cfa5N_7c.js.map} +1 -1
- comfyui_frontend_package/static/assets/{useSubscriptionDialog-Chxkdny5.js → useSubscriptionDialog-792qfEJ2.js} +3 -3
- comfyui_frontend_package/static/assets/{useSubscriptionDialog-Chxkdny5.js.map → useSubscriptionDialog-792qfEJ2.js.map} +1 -1
- comfyui_frontend_package/static/assets/useSubscriptionDialog-B-eGeK3j.js +1 -0
- comfyui_frontend_package/static/assets/{userStore-BkgQPjq6.js → userStore-BAS9m9W6.js} +2 -2
- comfyui_frontend_package/static/assets/{userStore-BkgQPjq6.js.map → userStore-BAS9m9W6.js.map} +1 -1
- comfyui_frontend_package/static/assets/vendor-three-BFcUNSs9.js.map +1 -1
- comfyui_frontend_package/static/index.html +1 -1
- {comfyui_frontend_package-1.38.5.dist-info → comfyui_frontend_package-1.38.6.dist-info}/METADATA +1 -1
- {comfyui_frontend_package-1.38.5.dist-info → comfyui_frontend_package-1.38.6.dist-info}/RECORD +126 -126
- comfyui_frontend_package/static/assets/AudioPreviewPlayer-BoEdyGI_.js +0 -1
- comfyui_frontend_package/static/assets/CloudRunButtonWrapper-hQc4BNkX.js +0 -3
- comfyui_frontend_package/static/assets/ComfyQueueButton-BbQnRThI.js +0 -1
- comfyui_frontend_package/static/assets/GraphView-BCkpNGgz.js.map +0 -1
- comfyui_frontend_package/static/assets/Load3D-DHBmC_AU.js +0 -1
- comfyui_frontend_package/static/assets/WidgetInputNumber-DGKypM5j.js +0 -3
- comfyui_frontend_package/static/assets/WidgetInputNumber-DGKypM5j.js.map +0 -1
- comfyui_frontend_package/static/assets/WidgetSelect-DsJGH12l.js +0 -1
- comfyui_frontend_package/static/assets/api-CUAc7rDA.js.map +0 -1
- comfyui_frontend_package/static/assets/auth-D3RiiqZ8.js +0 -1
- comfyui_frontend_package/static/assets/firebaseAuthStore-CZgxeMyf.js +0 -1
- comfyui_frontend_package/static/assets/releaseStore-CubqSv5t.js +0 -1
- comfyui_frontend_package/static/assets/useSubscriptionDialog-BzMzio2H.js +0 -1
- {comfyui_frontend_package-1.38.5.dist-info → comfyui_frontend_package-1.38.6.dist-info}/WHEEL +0 -0
- {comfyui_frontend_package-1.38.5.dist-info → comfyui_frontend_package-1.38.6.dist-info}/top_level.txt +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./firebaseAuthStore-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./firebaseAuthStore-DnNaPbuZ.js","./vendor-primevue-DcMRXJN3.js","./vendor-other-DlQF6V2E.js","./rolldown-runtime-BN4meiq5.js","./vendor-other-CaaUC6Qe.css","./dialogService-YG0RH337.js","./_plugin-vue_export-helper-PHE0iSCb.js","./vendor-vue-D9IUuwPJ.js","./vendor-three-BFcUNSs9.js","./vendor-tiptap-_UqYL7N_.js","./vendor-xterm-BU_lcTPR.js","./vendor-xterm-kHJ-D0s7.css","./PanelTemplate-BJda9e5J.js","./src-DTrob8OL.js","./Button-Do2I1OAA.js","./vendor-reka-ui-CmnTduBl.js","./Slider-De1ykl8L.js","./useErrorHandling-Cfa5N_7c.js","./remoteConfig-CZcEXsZS.js","./userStore-BAS9m9W6.js","./colorUtil-CzxntCbX.js","./markdownRendererUtil-DglHsU8t.js","./dialogService-BMbgJ9MG.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
var Xn=Object.defineProperty;var h=(o,e)=>Xn(o,"name",{value:e,configurable:!0});import{r as Yn}from"./rolldown-runtime-BN4meiq5.js";import{dt as R}from"./vendor-primevue-DcMRXJN3.js";import{Ar as ro,Dr as Qn,Er as qt,Ir as Zn,Ji as Jn,Or as ei,Qr as pe,Tr as ti,Vi as oi,Wr as $t,di as Ce,jr as c,ko as ni,kr as ii,qr as si,ti as ai,ui as lo,za as At,zo as Ze}from"./vendor-other-DlQF6V2E.js";import{p as ri,t as li}from"./vendor-vue-D9IUuwPJ.js";import{t as uo}from"./colorUtil-CzxntCbX.js";import{n as Ke,t as di}from"./widget-DNFXpyU8.js";function Uo(){return"electronAPI"in window&&window.electronAPI!==void 0}h(Uo,"isElectron");function ui(){return window.electronAPI}h(ui,"electronAPI");function wS(){ui()?.showContextMenu()}h(wS,"showNativeSystemMenu");function SS(){return Uo()&&!!window.navigator.windowControlsOverlay?.visible}h(SS,"isNativeWindow");var Wo="localhost";const IS=Wo==="desktop"||Uo(),ke=Wo==="cloud";var ci={supports_preview_metadata:!0,supports_manager_v4_ui:!0};const nt=ri("toast",()=>{const o=Ze([]),e=Ze([]),t=Ze(!1);function n(r){o.value=[...o.value,r]}h(n,"add");function i(r){e.value=[...e.value,r]}h(i,"remove");function s(){t.value=!0}h(s,"removeAll");function a(r){n({severity:"warn",summary:"Alert",detail:r})}return h(a,"addAlert"),{messagesToAdd:o,messagesToRemove:e,removeAllRequested:t,add:n,remove:i,removeAll:s,addAlert:a}});let CS=(function(o){return o.Cloud="cloud",o.Local="local",o.Desktop="desktop",o.Mac="mac",o.Windows="windows",o})({});var pi=c.enum(["LG","Vue"]);const W=c.union([c.number().int(),c.string()]);var Go=c.string(),Oe=c.union([c.number().int(),c.string().transform(o=>parseInt(o)).refine(o=>!isNaN(o),{message:"Invalid number"})]),Lt=c.union([c.string(),c.array(c.string()),c.number()]),Ve=c.union([c.object({0:c.number(),1:c.number()}).passthrough().transform(o=>[o[0],o[1]]),c.tuple([c.number(),c.number()])]),to=c.object({name:c.string(),url:c.string().url(),hash:c.string().optional(),hash_type:c.string().optional(),directory:c.string()}),mi=c.object({lastGroupId:c.number(),lastNodeId:c.number(),lastLinkId:c.number(),lastRerouteId:c.number()}).passthrough(),hi=c.tuple([c.number(),W,Oe,W,Oe,Lt]),gi=c.object({id:c.number(),parentId:c.number()}).passthrough(),Kt=c.object({id:c.number(),origin_id:W,origin_slot:Oe,target_id:W,target_slot:Oe,type:Lt,parentId:c.number().optional()}).passthrough(),Ho=c.object({id:c.number(),parentId:c.number().optional(),pos:Ve,linkIds:c.array(c.number()).nullish(),floating:c.object({slotType:c.enum(["input","output"])}).optional()}).passthrough(),fi=c.object({name:c.string(),type:Lt,links:c.array(c.number()).nullable().optional(),slot_index:Oe.optional()}).passthrough(),jo=c.object({name:Go,type:Lt,link:c.number().nullable().optional(),slot_index:Oe.optional()}).passthrough(),qo=c.object({collapsed:c.boolean().optional(),pinned:c.boolean().optional(),allow_interaction:c.boolean().optional(),horizontal:c.boolean().optional(),skip_repeated_outputs:c.boolean().optional()}).passthrough(),_i=/^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/,yi=/^(?!-)(?!.*--)[a-zA-Z0-9-]+(?<!-)$/,bi=/^[0-9a-f]{4,40}$/i,vi=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-z-]+(?:\.[\da-z-]+)*))?(?:\+([\da-z-]+(?:\.[\da-z-]+)*))?$/,$o=c.string().min(1).max(100).regex(_i,{message:"ID can only contain ASCII letters, digits, '_', '-', and '.'"}).refine(o=>!/^[_\-.]|[_\-.]$/.test(o),{message:"ID must not start or end with '_', '-', or '.'"}),ki=$o,wi=$o,Si=c.string().min(1).max(39).regex(yi,"Invalid GitHub username/org"),Ii=c.string().regex(/^[^/]+\/[^/]+$/,"Invalid format. Must be 'github-user/repo-name'").transform(o=>o.split("/")).refine(([o,e])=>Si.safeParse(o).success&&wi.safeParse(e).success,"Invalid aux_id: Must be valid 'github-username/github-repo-name'").transform(([o,e])=>`${o}/${e}`),Ci=c.string().superRefine((o,e)=>{bi.test(o)||e.addIssue({code:c.ZodIssueCode.custom,message:`Node pack version has invalid Git commit hash: "${o}"`})}),Ti=c.string().superRefine((o,e)=>{vi.test(o)||e.addIssue({code:c.ZodIssueCode.custom,message:`Node pack version has invalid semantic version: "${o}"`})}),Li=c.union([c.string().transform(o=>o.replace(/^v/,"")).pipe(c.union([Ti,Ci])),c.literal("unknown")]),Ei=c.object({"Node name for S&R":c.string().optional(),cnr_id:ki.optional(),aux_id:Ii.optional(),ver:Li.optional(),models:c.array(to).optional()}).passthrough(),Ko=c.union([c.array(c.any()),c.record(c.any())]),Xo=c.object({id:W,type:c.string(),pos:Ve,size:Ve,flags:qo,order:c.number(),mode:c.number(),inputs:c.array(jo).optional(),outputs:c.array(fi).optional(),properties:Ei,widgets_values:Ko.optional(),color:c.string().optional(),bgcolor:c.string().optional()}).passthrough(),_t=jo.extend({id:c.string().uuid(),type:c.string(),linkIds:c.array(c.number()).optional()}),Ni=c.object({id:W,type:c.string().uuid(),pos:Ve,size:Ve,flags:qo,order:c.number(),mode:c.number(),inputs:c.array(_t).optional(),outputs:c.array(_t).optional(),widgets_values:Ko.optional(),color:c.string().optional(),bgcolor:c.string().optional()}).passthrough(),Yo=c.object({id:c.number().optional(),title:c.string(),bounding:c.tuple([c.number(),c.number(),c.number(),c.number()]),color:c.string().optional(),font_size:c.number().optional(),locked:c.boolean().optional()}).passthrough(),xi=c.object({scale:c.number(),offset:Ve}).passthrough(),oo=c.object({links_ontop:c.boolean().optional(),align_to_grid:c.boolean().optional()}).passthrough(),Qo=c.object({ds:xi.optional(),frontendVersion:c.string().optional(),linkExtensions:c.array(gi).optional(),reroutes:c.array(Ho).optional(),workflowRendererVersion:pi.optional()}).passthrough(),Ai=c.object({subgraphs:c.lazy(()=>c.array(no))}),Zo=c.object({id:c.string().uuid().optional(),revision:c.number().optional(),config:oo.optional().nullable(),subgraphs:c.array(Ni).optional()});const Di=Zo.extend({id:c.string().uuid().optional(),revision:c.number().optional(),last_node_id:W,last_link_id:c.number(),nodes:c.array(Xo),links:c.array(hi),floatingLinks:c.array(Kt).optional(),groups:c.array(Yo).optional(),config:oo.optional().nullable(),extra:Qo.optional().nullable(),version:c.number(),models:c.array(to).optional(),definitions:Ai.optional()}).passthrough(),Jo=Zo.extend({id:c.string().uuid().optional(),revision:c.number().optional(),version:c.literal(1),config:oo.optional().nullable(),state:mi,groups:c.array(Yo).optional(),nodes:c.array(Xo),links:c.array(Kt).optional(),floatingLinks:c.array(Kt).optional(),reroutes:c.array(Ho).optional(),extra:Qo.optional().nullable(),models:c.array(to).optional(),definitions:c.object({subgraphs:c.lazy(()=>c.array(no))}).optional()}).passthrough();var co=c.object({id:W,bounding:c.tuple([c.number(),c.number(),c.number(),c.number()]),pinned:c.boolean().optional()}),Oi=c.object({id:c.string(),name:c.string()}),no=Jo.extend({id:c.string().uuid(),revision:c.number(),name:c.string(),inputNode:co,outputNode:co,inputs:c.array(_t).optional(),outputs:c.array(_t).optional(),widgets:c.array(Oi).optional(),definitions:c.object({subgraphs:c.lazy(()=>no.array())}).optional()}).passthrough();function TS(o){return o!==null&&typeof o=="object"&&"id"in o&&"name"in o&&"nodes"in o&&Array.isArray(o.nodes)&&"inputNode"in o&&"outputNode"in o}h(TS,"isSubgraphDefinition");var Pi=c.object({version:c.number()});async function Mi(o,e=console.warn){const t=Pi.safeParse(o);let n;if(t.success)t.data.version===1?n=await Jo.safeParseAsync(o):n=await Di.safeParseAsync(o);else return e(`Workflow does not contain a valid version. Zod error:
|
|
3
3
|
${ro(t.error)}`),null;return n.success?n.data:(e(`Invalid workflow against zod schema:
|
|
4
4
|
${ro(n.error)}`),null)}h(Mi,"validateComfyWorkflow");var Ri=c.union([c.any(),c.tuple([W,Oe])]),Fi=c.object({inputs:c.record(Go,Ri),class_type:c.string(),_meta:c.object({title:c.string()})});c.record(W,Fi);var zi=class ct{static{h(this,"ContextMenu")}options;parentMenu;root;current_submenu;lock;controller=new AbortController;constructor(e,t){t||={},this.options=t;const n=t.parentMenu;n&&(n instanceof ct?(this.parentMenu=n,this.parentMenu.lock=!0,this.parentMenu.current_submenu=this):(console.error("parentMenu must be of class ContextMenu, ignoring it"),t.parentMenu=void 0),n.options?.className==="dark"&&(t.className="dark"));const i=t.event?t.event.constructor.name:null;i!=="MouseEvent"&&i!=="CustomEvent"&&i!=="PointerEvent"&&(console.error(`Event passed to ContextMenu is not of type MouseEvent or CustomEvent. Ignoring it. (${i})`),t.event=void 0);const s=document.createElement("div");let a="litegraph litecontextmenu litemenubar-panel";t.className&&(a+=` ${t.className}`),s.className=a,s.style.minWidth="100",s.style.minHeight="100";const{signal:r}=this.controller,l={capture:!0,signal:r};if(this.parentMenu||document.addEventListener("pointerdown",m=>{m.target instanceof Node&&!this.containsNode(m.target)&&this.close()},l),s.addEventListener("pointerup",m=>m.preventDefault(),l),s.addEventListener("contextmenu",m=>{m.button===2&&m.preventDefault()},l),s.addEventListener("pointerdown",m=>{m.button==2&&(this.close(),m.preventDefault())},l),this.root=s,t.title){const m=document.createElement("div");m.className="litemenu-title",m.innerHTML=t.title,s.append(m)}for(let m=0;m<e.length;m++){const g=e[m];let f=Array.isArray(e)?g:String(m);typeof f!="string"&&(f=f!=null?f.content===void 0?String(f):f.content:f),this.addItem(f,g,t)}const d=t.event?.target?.ownerDocument||document;d.fullscreenElement?d.fullscreenElement.append(s):d.body.append(s);let u=t.left||0,p=t.top||0;if(t.event){if(u=t.event.clientX-10,p=t.event.clientY-10,t.title&&(p-=20),n){const f=n.root.getBoundingClientRect();u=f.left+f.width}const m=document.body.getBoundingClientRect(),g=s.getBoundingClientRect();m.height==0&&console.error("document.body height is 0. That is dangerous, set html,body { height: 100%; }"),m.width&&u>m.width-g.width-10&&(u=m.width-g.width-10),m.height&&p>m.height-g.height-10&&(p=m.height-g.height-10)}s.style.left=`${u}px`,s.style.top=`${p}px`,_.context_menu_scaling&&t.scale&&(s.style.transform=`scale(${Math.round(t.scale*4)*.25})`)}containsNode(e,t=new Set){return t.has(this)?!1:(t.add(this),this.current_submenu?.containsNode(e,t)||this.root.contains(e))}addItem(e,t,n){n||={};const i=document.createElement("div");i.className="litemenu-entry submenu";let s=!1;if(t===null)i.classList.add("separator");else{const u=e===null?"":String(e);typeof t=="string"?i.innerHTML=u:(i.innerHTML=t?.title??u,t.disabled&&(s=!0,i.classList.add("disabled"),i.setAttribute("aria-disabled","true")),(t.submenu||t.has_submenu)&&(i.classList.add("has_submenu"),i.setAttribute("aria-haspopup","true"),i.setAttribute("aria-expanded","false")),t.className&&(i.className+=` ${t.className}`)),i.value=t,i.setAttribute("role","menuitem"),typeof t=="function"?(i.dataset.value=String(e),i.onclick_callback=t):i.dataset.value=String(t)}this.root.append(i),s||i.addEventListener("click",d),!s&&n.autoopen&&i.addEventListener("pointerenter",r);const a=h(()=>{const u=this.root.querySelectorAll("div.litemenu-entry.has_submenu");if(u)for(const p of u)p.setAttribute("aria-expanded","false");i.setAttribute("aria-expanded","true")},"setAriaExpanded");function r(u){const p=this.value;!p||!p.has_submenu||(d.call(this,u),a())}h(r,"inner_over");const l=this;function d(u){const p=this.value;let m=!0;if(l.current_submenu?.close(u),(p?.has_submenu||p?.submenu)&&a(),n.callback&&n.callback.call(this,p,n,u,l,n.node)===!0&&(m=!1),typeof p=="object"&&(p.callback&&!n.ignore_item_callbacks&&p.disabled!==!0&&p.callback.call(this,p,n,u,l,n.extra)===!0&&(m=!1),p.submenu)){if(!p.submenu.options)throw"ContextMenu submenu needs options";new l.constructor(p.submenu.options,{callback:p.submenu.callback,event:u,parentMenu:l,ignore_item_callbacks:p.submenu.ignore_item_callbacks,title:p.submenu.title,extra:p.submenu.extra,autoopen:n.autoopen}),m=!1}m&&!l.lock&&l.close()}return h(d,"inner_onclick"),i}close(e,t){this.controller.abort(),this.root.remove(),this.parentMenu&&!t&&(this.parentMenu.lock=!1,this.parentMenu.current_submenu=void 0,e===void 0?this.parentMenu.close():e&&!ct.isCursorOverElement(e,this.parentMenu.root)&&ct.trigger(this.parentMenu.root,`${_.pointerevents_method}leave`,e)),this.current_submenu?.close(e,!0)}static trigger(e,t,n){const i=document.createEvent("CustomEvent");return i.initCustomEvent(t,!0,!0,n),e.dispatchEvent&&e.dispatchEvent(i),i}getTopMenu(){return this.options.parentMenu?this.options.parentMenu.getTopMenu():this}getFirstEvent(){return this.options.parentMenu?this.options.parentMenu.getFirstEvent():this.options.event}static isCursorOverElement(e,t){const n=e.clientX,i=e.clientY,s=t.getBoundingClientRect();return s?i>s.top&&i<s.top+s.height&&n>s.left&&n<s.left+s.width:!1}};let j=(function(o){return o[o.INPUT=1]="INPUT",o[o.OUTPUT=2]="OUTPUT",o})({}),M=(function(o){return o[o.BOX=1]="BOX",o[o.ROUND=2]="ROUND",o[o.CIRCLE=3]="CIRCLE",o[o.CARD=4]="CARD",o[o.ARROW=5]="ARROW",o[o.GRID=6]="GRID",o[o.HollowCircle=7]="HollowCircle",o})({}),te=(function(o){return o[o.Nothing=0]="Nothing",o[o.Node=1]="Node",o[o.Group=2]="Group",o[o.Reroute=4]="Reroute",o[o.Link=8]="Link",o[o.RerouteSlot=32]="RerouteSlot",o[o.SubgraphIoNode=64]="SubgraphIoNode",o[o.SubgraphIoSlot=128]="SubgraphIoSlot",o})({}),O=(function(o){return o[o.NONE=0]="NONE",o[o.UP=1]="UP",o[o.DOWN=2]="DOWN",o[o.LEFT=3]="LEFT",o[o.RIGHT=4]="RIGHT",o[o.CENTER=5]="CENTER",o})({}),ie=(function(o){return o[o.HIDDEN_LINK=-1]="HIDDEN_LINK",o[o.STRAIGHT_LINK=0]="STRAIGHT_LINK",o[o.LINEAR_LINK=1]="LINEAR_LINK",o[o.SPLINE_LINK=2]="SPLINE_LINK",o})({}),re=(function(o){return o[o.None=0]="None",o[o.Circle=1]="Circle",o[o.Arrow=2]="Arrow",o})({}),se=(function(o){return o[o.NORMAL_TITLE=0]="NORMAL_TITLE",o[o.NO_TITLE=1]="NO_TITLE",o[o.TRANSPARENT_TITLE=2]="TRANSPARENT_TITLE",o[o.AUTOHIDE_TITLE=3]="AUTOHIDE_TITLE",o})({}),H=(function(o){return o[o.ALWAYS=0]="ALWAYS",o[o.ON_EVENT=1]="ON_EVENT",o[o.NEVER=2]="NEVER",o[o.ON_TRIGGER=3]="ON_TRIGGER",o[o.BYPASS=4]="BYPASS",o})({}),Bi=(function(o){return o.EASE_IN_OUT_QUAD="easeInOutQuad",o})({}),ee=(function(o){return o[o.None=0]="None",o[o.Top=1]="Top",o[o.Bottom=2]="Bottom",o[o.Middle=4]="Middle",o[o.Left=8]="Left",o[o.Right=16]="Right",o[o.Centre=32]="Centre",o[o.TopLeft=9]="TopLeft",o[o.TopCentre=33]="TopCentre",o[o.TopRight=17]="TopRight",o[o.MidLeft=12]="MidLeft",o[o.MidCentre=36]="MidCentre",o[o.MidRight=20]="MidRight",o[o.BottomLeft=10]="BottomLeft",o[o.BottomCentre=34]="BottomCentre",o[o.BottomRight=18]="BottomRight",o})({});function le(o,e){return(o&e)===e}h(le,"hasFlag");function Ue(o,e){return Math.sqrt((e[0]-o[0])*(e[0]-o[0])+(e[1]-o[1])*(e[1]-o[1]))}h(Ue,"distance");function Vi(o,e,t,n){return(t-o)*(t-o)+(n-e)*(n-e)}h(Vi,"dist2");function G(o,e,t,n,i,s){return o>=t&&o<t+i&&e>=n&&e<n+s}h(G,"isInRectangle");function We(o,e){return o[0]>=e[0]&&o[0]<e[0]+e[2]&&o[1]>=e[1]&&o[1]<e[1]+e[3]}h(We,"isPointInRect");function yt(o,e,t){return o>=t[0]&&o<t[0]+t[2]&&e>=t[1]&&e<t[1]+t[3]}h(yt,"isInRect");function Ui(o,e,t,n,i,s){return t<o&&t+i>o&&n<e&&n+s>e}h(Ui,"isInsideRectangle");function Le(o,e){const t=o[0]+o[2],n=o[1]+o[3],i=e[0]+e[2],s=e[1]+e[3];return!(o[0]>i||o[1]>s||t<e[0]||n<e[1])}h(Le,"overlapBounding");function Wi(o){return[o[0]+o[2]*.5,o[1]+o[3]*.5]}h(Wi,"getCentre");function Gi(o,e){return yt(e[0]+e[2]*.5,e[1]+e[3]*.5,o)}h(Gi,"containsCentre");function en(o,e){const t=o[0]+o[2],n=o[1]+o[3],i=e[0]+e[2],s=e[1]+e[3];return!(o[0]===e[0]&&o[1]===e[1]&&t===i&&n===s)&&o[0]<=e[0]&&o[1]<=e[1]&&t>=i&&n>=s}h(en,"containsRect");function et(o,e=10){const t=[1/0,1/0,-1/0,-1/0];for(const n of o){const i=n.boundingRect;t[0]=Math.min(t[0],i[0]),t[1]=Math.min(t[1],i[1]),t[2]=Math.max(t[2],i[0]+i[2]),t[3]=Math.max(t[3],i[1]+i[3])}return t.every(n=>isFinite(n))?[t[0]-e,t[1]-e,t[2]-t[0]+2*e,t[3]-t[1]+2*e]:null}h(et,"createBounds");function xe(o,e){return e?(o[0]=e*Math.round(o[0]/e),o[1]=e*Math.round(o[1]/e),!0):!1}h(xe,"snapPoint");function Hi(o,e,[t,n,i,s],[a,r]=[0,0]){return le(e,ee.Left)?o[0]=t+a:le(e,ee.Right)?o[0]=t+i-a-o[2]:le(e,ee.Centre)&&(o[0]=t+i*.5-o[2]*.5),le(e,ee.Top)?o[1]=n+r:le(e,ee.Bottom)?o[1]=n+s-r-o[3]:le(e,ee.Middle)&&(o[1]=n+s*.5-o[3]*.5),o}h(Hi,"alignToContainer");function po(o,e,[t,n,i,s],[a,r]=[0,0]){return le(e,ee.Left)?o[0]=t-a-o[2]:le(e,ee.Right)?o[0]=t+i+a:le(e,ee.Centre)&&(o[0]=t+i*.5-o[2]*.5),le(e,ee.Top)?o[1]=n-r-o[3]:le(e,ee.Bottom)?o[1]=n+s+r:le(e,ee.Middle)&&(o[1]=n+s*.5-o[3]*.5),o}h(po,"alignOutsideContainer");var ji=class{static{h(this,"CurveEditor")}points;selected;nearest;size;must_update;margin;_nearest;constructor(o){this.points=o,this.selected=-1,this.nearest=-1,this.size=null,this.must_update=!0,this.margin=5}static sampleCurve(o,e){if(e){for(let t=0;t<e.length-1;++t){const n=e[t],i=e[t+1];if(i[0]<o)continue;const s=i[0]-n[0];if(Math.abs(s)<1e-5)return n[1];const a=(o-n[0])/s;return n[1]*(1-a)+i[1]*a}return 0}}draw(o,e,t,n,i,s=!1){const a=this.points;if(!a)return;this.size=e;const r=e[0]-this.margin*2,l=e[1]-this.margin*2;i=i||"#666",o.save(),o.translate(this.margin,this.margin),n&&(o.fillStyle="#111",o.fillRect(0,0,r,l),o.fillStyle="#222",o.fillRect(r*.5,0,1,l),o.strokeStyle="#333",o.strokeRect(0,0,r,l)),o.strokeStyle=i,s&&(o.globalAlpha=.5),o.beginPath();for(const d of a)o.lineTo(d[0]*r,(1-d[1])*l);if(o.stroke(),o.globalAlpha=1,!s)for(const[d,u]of a.entries())o.fillStyle=this.selected==d?"#FFF":this.nearest==d?"#DDD":"#AAA",o.beginPath(),o.arc(u[0]*r,(1-u[1])*l,2,0,Math.PI*2),o.fill();o.restore()}onMouseDown(o,e){const t=this.points;if(!t||o[1]<0)return;if(this.size==null)throw new Error("CurveEditor.size was null or undefined.");const n=this.size[0]-this.margin*2,i=this.size[1]-this.margin*2,s=o[0]-this.margin,a=o[1]-this.margin,r=[s,a],l=30/e.ds.scale;if(this.selected=this.getCloserPoint(r,l),this.selected==-1){const d=[s/n,1-a/i];t.push(d),t.sort(function(u,p){return u[0]-p[0]}),this.selected=t.indexOf(d),this.must_update=!0}if(this.selected!=-1)return!0}onMouseMove(o,e){const t=this.points;if(!t)return;const n=this.selected;if(n<0)return;if(this.size==null)throw new Error("CurveEditor.size was null or undefined.");const i=(o[0]-this.margin)/(this.size[0]-this.margin*2),s=(o[1]-this.margin)/(this.size[1]-this.margin*2),a=[o[0]-this.margin,o[1]-this.margin],r=30/e.ds.scale;this._nearest=this.getCloserPoint(a,r);const l=t[n];if(l){const d=n==0||n==t.length-1;if(!d&&(o[0]<-10||o[0]>this.size[0]+10||o[1]<-10||o[1]>this.size[1]+10)){t.splice(n,1),this.selected=-1;return}d?l[0]=n==0?0:1:l[0]=pe(i,0,1),l[1]=1-pe(s,0,1),t.sort(function(u,p){return u[0]-p[0]}),this.selected=t.indexOf(l),this.must_update=!0}}onMouseUp(){return this.selected=-1,!1}getCloserPoint(o,e){const t=this.points;if(!t)return-1;if(e=e||30,this.size==null)throw new Error("CurveEditor.size was null or undefined.");const n=this.size[0]-this.margin*2,i=this.size[1]-this.margin*2,s=t.length,a=[0,0];let r=1e6,l=-1;for(let d=0;d<s;++d){const u=t[d];a[0]=u[0]*n,a[1]=(1-u[1])*i;const p=Ue(o,a);p>r||p>e||(l=d,r=p)}return l}},tn=class{static{h(this,"DragAndScale")}state;lastState={offset:[0,0],scale:0};max_scale;min_scale;enabled;last_mouse;element;visible_area;dragging;viewport;get offset(){return this.state.offset}set offset(o){this.state.offset[0]=o[0],this.state.offset[1]=o[1]}get scale(){return this.state.scale}set scale(o){this.state.scale=o}constructor(o){this.state={offset:[0,0],scale:1},this.max_scale=10,this.min_scale=.1,this.enabled=!0,this.last_mouse=[0,0],this.visible_area=new X,this.element=o}#e(){const o=this.state,e=this.lastState;return o.scale!==e.scale||o.offset[0]!==e.offset[0]||o.offset[1]!==e.offset[1]}computeVisibleArea(o){const{scale:e,offset:t,visible_area:n}=this;if(this.#e()&&(this.onChanged?.(e,t),qi(this.state,this.lastState)),!this.element){n[0]=n[1]=n[2]=n[3]=0;return}let{width:i,height:s}=this.element,a=-t[0],r=-t[1];o&&(a+=o[0]/e,r+=o[1]/e,i=o[2],s=o[3]);const l=a+i/e,d=r+s/e;n[0]=a,n[1]=r,n.resizeBottomRight(l,d)}toCanvasContext(o){o.scale(this.scale,this.scale),o.translate(this.offset[0],this.offset[1])}convertOffsetToCanvas(o){return[(o[0]+this.offset[0])*this.scale,(o[1]+this.offset[1])*this.scale]}convertCanvasToOffset(o,e){return e=e||[0,0],e[0]=o[0]/this.scale-this.offset[0],e[1]=o[1]/this.scale-this.offset[1],e}mouseDrag(o,e){this.offset[0]+=o/this.scale,this.offset[1]+=e/this.scale,this.onredraw?.(this)}changeScale(o,e,t=!0){if(o<this.min_scale?o=this.min_scale:o>this.max_scale&&(o=this.max_scale),o==this.scale)return;const n=this.element.getBoundingClientRect();if(!n)return;e=e??[n.width*.5,n.height*.5];const i=[e[0]-n.x,e[1]-n.y],s=this.convertCanvasToOffset(i);this.scale=o,t&&Math.abs(this.scale-1)<.01&&(this.scale=1);const a=this.convertCanvasToOffset(i),r=[a[0]-s[0],a[1]-s[1]];this.offset[0]+=r[0],this.offset[1]+=r[1],this.onredraw?.(this)}changeDeltaScale(o,e){this.changeScale(this.scale*o,e)}fitToBounds(o,{zoom:e=.75}={}){const[t,n]=this.element.width===300&&this.element.height===150?[1920,1080]:[this.element.width,this.element.height],i=t/window.devicePixelRatio,s=n/window.devicePixelRatio;let a=this.scale;if(e>0){const p=e*i/Math.max(o[2],300),m=e*s/Math.max(o[3],300);a=Math.min(p,m,this.max_scale)}const r=i/a,l=s/a,d=-o[0]-o[2]*.5+r*.5,u=-o[1]-o[3]*.5+l*.5;this.offset[0]=d,this.offset[1]=u,this.scale=a}animateToBounds(o,e,{duration:t=350,zoom:n=.75,easing:i=Bi.EASE_IN_OUT_QUAD}={}){if(!(t>0))throw new RangeError("Duration must be greater than 0");const s={linear:h(I=>I,"linear"),easeInQuad:h(I=>I*I,"easeInQuad"),easeOutQuad:h(I=>I*(2-I),"easeOutQuad"),easeInOutQuad:h(I=>I<.5?2*I*I:-1+(4-2*I)*I,"easeInOutQuad")},a=s[i]??s.linear,r=performance.now(),l=this.element.width/window.devicePixelRatio,d=this.element.height/window.devicePixelRatio,u=this.offset[0],p=this.offset[1],m=u-l/this.scale,g=p-d/this.scale;let f=this.scale;if(n>0){const I=n*l/Math.max(o[2],300),P=n*d/Math.max(o[3],300);f=Math.min(I,P,this.max_scale)}const y=l/f,b=d/f,v=-o[0]-o[2]*.5+y*.5,k=-o[1]-o[3]*.5+b*.5,w=v-y,S=k-b,E=h(I=>{const P=I-r,A=Math.min(P/t,1),F=a(A),T=u+(v-u)*F,$=p+(k-p)*F;if(this.offset[0]=T,this.offset[1]=$,n>0){const V=m+(w-m)*F,oe=g+(S-g)*F,x=Math.abs(V-T),me=Math.abs(oe-$);this.scale=Math.min(l/x,d/me)}e(),A<1?C=requestAnimationFrame(E):cancelAnimationFrame(C)},"animate");let C=requestAnimationFrame(E)}reset(){this.scale=1,this.offset[0]=0,this.offset[1]=0}};function qi(o,e){e.scale=o.scale,e.offset[0]=o.offset[0],e.offset[1]=o.offset[1]}h(qi,"copyState");const bt="00000000-0000-0000-0000-000000000000";var $i=new Uint32Array(31);function fe(){if(typeof crypto?.randomUUID=="function")return crypto.randomUUID();if(typeof crypto?.getRandomValues=="function"){const o=crypto.getRandomValues($i);let e=0;return"10000000-1000-4000-8000-100000000000".replaceAll(/[018]/g,t=>(Number(t)^o[e++]*3725290298461914e-24>>Number(t)*.25).toString(16))}return"10000000-1000-4000-8000-100000000000".replaceAll(/[018]/g,o=>(Number(o)^Math.random()*16>>Number(o)*.25).toString(16))}h(fe,"createUuidv4");const on=h(o=>Math.max(0,o-(_.NODE_TITLE_HEIGHT||0)),"removeNodeTitleHeight");let ue=(function(o){return o.Canvas="canvas",o.Vue="vue",o.DOM="dom",o.External="external",o})({});const Dt={DEFAULT_BOUNDS:{x:-1e4,y:-1e4,width:2e4,height:2e4},MAX_DEPTH:6,MAX_ITEMS_PER_NODE:4},mo={CHANGE_DETECTION_INTERVAL:16,SPATIAL_CACHE_TTL:1e3,SPATIAL_CACHE_MAX_SIZE:100,BATCH_UPDATE_DELAY:4},Ot={USER_PREFIX:"user-",ID_LENGTH:9,DEFAULT_SOURCE:ue.External};function LS(o,e){return{x:o,y:e}}h(LS,"toPoint");function it(o,e){return o.x===e.x&&o.y===e.y}h(it,"isPointEqual");function st(o,e){return o.x===e.x&&o.y===e.y&&o.width===e.width&&o.height===e.height}h(st,"isBoundsEqual");function ES(o,e){return o.width===e.width&&o.height===e.height}h(ES,"isSizeEqual");function Pt(o,e){return o.x>=e.x&&o.x<=e.x+e.width&&o.y>=e.y&&o.y<=e.y+e.height}h(Pt,"pointInBounds");function Ki(o,e){return!(o.x+o.width<e.x||e.x+e.width<o.x||o.y+o.height<e.y||e.y+e.height<o.y)}h(Ki,"boundsIntersect");function ho(o,e){return`${o}:${e??"final"}`}h(ho,"makeLinkSegmentKey");const Pe={id:"unknown-node",position:{x:0,y:0},size:{width:100,height:50},zIndex:0,visible:!0,bounds:{x:0,y:0,width:100,height:50}};function go(o){const e=new qt;return e.set("id",o.id),e.set("position",o.position),e.set("size",o.size),e.set("zIndex",o.zIndex),e.set("visible",o.visible),e.set("bounds",o.bounds),e}h(go,"layoutToYNode");function Me(o,e,t){return o.get(e)??t}h(Me,"getOr");function be(o){return{id:Me(o,"id",Pe.id),position:Me(o,"position",Pe.position),size:Me(o,"size",Pe.size),zIndex:Me(o,"zIndex",Pe.zIndex),visible:Me(o,"visible",Pe.visible),bounds:Me(o,"bounds",Pe.bounds)}}h(be,"yNodeToLayout");var fo=class Xe{static{h(this,"QuadNode")}bounds;depth;maxDepth;maxItems;items=[];children=null;divided=!1;constructor(e,t=0,n=5,i=4){this.bounds=e,this.depth=t,this.maxDepth=n,this.maxItems=i}insert(e){if(!this.contains(e.bounds))return!1;if(this.items.length<this.maxItems&&!this.divided)return this.items.push(e),!0;if(!this.divided&&this.depth<this.maxDepth&&this.subdivide(),this.divided&&this.children){for(const t of this.children)if(t.insert(e))return!0}return this.items.push(e),!0}remove(e){const t=this.items.findIndex(n=>n.id===e.id);if(t!==-1)return this.items.splice(t,1),!0;if(this.divided&&this.children){for(const n of this.children)if(n.remove(e))return!0}return!1}query(e,t=[]){if(!this.intersects(e))return t;for(const n of this.items)this.boundsIntersect(n.bounds,e)&&t.push(n);if(this.divided&&this.children)for(const n of this.children)n.query(e,t);return t}subdivide(){const{x:e,y:t,width:n,height:i}=this.bounds,s=n/2,a=i/2;this.children=[new Xe({x:e,y:t,width:s,height:a},this.depth+1,this.maxDepth,this.maxItems),new Xe({x:e+s,y:t,width:s,height:a},this.depth+1,this.maxDepth,this.maxItems),new Xe({x:e,y:t+a,width:s,height:a},this.depth+1,this.maxDepth,this.maxItems),new Xe({x:e+s,y:t+a,width:s,height:a},this.depth+1,this.maxDepth,this.maxItems)],this.divided=!0;const r=[...this.items];this.items=[];for(const l of r){let d=!1;for(const u of this.children)if(u.insert(l)){d=!0;break}d||this.items.push(l)}}contains(e){return e.x>=this.bounds.x&&e.y>=this.bounds.y&&e.x+e.width<=this.bounds.x+this.bounds.width&&e.y+e.height<=this.bounds.y+this.bounds.height}intersects(e){return this.boundsIntersect(this.bounds,e)}boundsIntersect(e,t){return!(e.x+e.width<t.x||t.x+t.width<e.x||e.y+e.height<t.y||t.y+t.height<e.y)}getDebugInfo(){return{bounds:this.bounds,depth:this.depth,itemCount:this.items.length,divided:this.divided,children:this.children?.map(e=>e.getDebugInfo())}}},Xi=class{static{h(this,"QuadTree")}root;itemMap=new Map;options;constructor(o,e={}){this.options={maxDepth:e.maxDepth??5,maxItemsPerNode:e.maxItemsPerNode??4,minNodeSize:e.minNodeSize??50},this.root=new fo(o,0,this.options.maxDepth,this.options.maxItemsPerNode)}insert(o,e,t){const n={id:o,bounds:e,data:t};this.itemMap.has(o)&&this.remove(o);const i=this.root.insert(n);return i&&this.itemMap.set(o,n),i}remove(o){const e=this.itemMap.get(o);if(!e)return!1;const t=this.root.remove(e);return t&&this.itemMap.delete(o),t}update(o,e){const t=this.itemMap.get(o);if(!t)return!1;const n=t.data;return this.remove(o),this.insert(o,e,n)}query(o){return this.root.query(o).map(e=>e.data)}clear(){this.root=new fo(this.root.bounds,0,this.options.maxDepth,this.options.maxItemsPerNode),this.itemMap.clear()}get size(){return this.itemMap.size}getDebugInfo(){return{size:this.size,tree:this.root.getDebugInfo()}}},at=class{static{h(this,"SpatialIndexManager")}quadTree;queryCache;cacheSize=0;constructor(o){this.quadTree=new Xi(o??Dt.DEFAULT_BOUNDS,{maxDepth:Dt.MAX_DEPTH,maxItemsPerNode:Dt.MAX_ITEMS_PER_NODE}),this.queryCache=new Map}insert(o,e){this.quadTree.insert(o,e,o),this.invalidateCache()}update(o,e){this.quadTree.update(o,e),this.invalidateCache()}batchUpdate(o){for(const{nodeId:e,bounds:t}of o)this.quadTree.update(e,t);this.invalidateCache()}remove(o){this.quadTree.remove(o),this.invalidateCache()}query(o){const e=this.getCacheKey(o),t=this.queryCache.get(e);if(t){if(Date.now()-t.timestamp<mo.SPATIAL_CACHE_TTL)return t.result;this.queryCache.delete(e),this.cacheSize--}const n=this.quadTree.query(o);return this.addToCache(e,n),n}clear(){this.quadTree.clear(),this.invalidateCache()}get size(){return this.quadTree.size}getDebugInfo(){return{quadTreeInfo:this.quadTree.getDebugInfo(),cacheSize:this.cacheSize,cacheEntries:this.queryCache.size}}getCacheKey(o){return`${o.x},${o.y},${o.width},${o.height}`}addToCache(o,e){if(this.cacheSize>=mo.SPATIAL_CACHE_MAX_SIZE){const t=this.findOldestCacheEntry();t&&(this.queryCache.delete(t),this.cacheSize--)}this.queryCache.set(o,{result:e,timestamp:Date.now()}),this.cacheSize++}findOldestCacheEntry(){let o=null,e=1/0;for(const[t,n]of this.queryCache)n.timestamp<e&&(e=n.timestamp,o=t);return o}invalidateCache(){this.queryCache.clear(),this.cacheSize=0}},nn=Yn(ii(),1),Re=nn.default.getLogger("LayoutStore");function Mt(o){return Number(o)}h(Mt,"asRerouteId");function _o(o){return Number(o)}h(_o,"asLinkId");var Yi=class sn{static{h(this,"LayoutStoreImpl")}static REROUTE_DEFAULTS={id:0,position:{x:0,y:0},parentId:0,linkIds:[]};ydoc=new ti;ynodes;ylinks;yreroutes;yoperations;version=0;currentSource=Ot.DEFAULT_SOURCE;currentActor=`${Ot.USER_PREFIX}${Math.random().toString(36).substring(2,2+Ot.ID_LENGTH)}`;changeListeners=new Set;nodeRefs=new Map;nodeTriggers=new Map;linkLayouts=new Map;linkSegmentLayouts=new Map;slotLayouts=new Map;rerouteLayouts=new Map;spatialIndex;linkSegmentSpatialIndex;slotSpatialIndex;rerouteSpatialIndex;isDraggingVueNodes=Ze(!1);isResizingVueNodes=Ze(!1);constructor(){this.ynodes=this.ydoc.getMap("nodes"),this.ylinks=this.ydoc.getMap("links"),this.yreroutes=this.ydoc.getMap("reroutes"),this.yoperations=this.ydoc.getArray("operations"),this.spatialIndex=new at,this.linkSegmentSpatialIndex=new at,this.slotSpatialIndex=new at,this.rerouteSpatialIndex=new at,this.ynodes.observe(e=>{this.version++,e.changes.keys.forEach((t,n)=>{const i=this.nodeTriggers.get(n);i&&i()})}),this.ylinks.observe(e=>{this.version++,e.changes.keys.forEach((t,n)=>{this.handleLinkChange(t,n)})}),this.yreroutes.observe(e=>{this.version++,e.changes.keys.forEach((t,n)=>{this.handleRerouteChange(t,n)})})}getLinkField(e,t){return e.get(t)}getRerouteField(e,t,n=sn.REROUTE_DEFAULTS[t]){return e.get(t)??n}getNodeLayoutRef(e){let t=this.nodeRefs.get(e);return t||(t=ni((n,i)=>(this.nodeTriggers.set(e,i),{get:h(()=>{n();const s=this.ynodes.get(e);return s?be(s):null},"get"),set:h(s=>{if(s===null){const a=this.ynodes.get(e);a&&this.applyOperation({type:"deleteNode",entity:"node",nodeId:e,timestamp:Date.now(),source:this.currentSource,actor:this.currentActor,previousLayout:be(a)})}else{const a=this.ynodes.get(e);if(!a)this.applyOperation({type:"createNode",entity:"node",nodeId:e,layout:s,timestamp:Date.now(),source:this.currentSource,actor:this.currentActor});else{const r=be(a);(r.position.x!==s.position.x||r.position.y!==s.position.y)&&this.applyOperation({type:"moveNode",entity:"node",nodeId:e,position:s.position,previousPosition:r.position,timestamp:Date.now(),source:this.currentSource,actor:this.currentActor}),(r.size.width!==s.size.width||r.size.height!==s.size.height)&&this.applyOperation({type:"resizeNode",entity:"node",nodeId:e,size:s.size,previousSize:r.size,timestamp:Date.now(),source:this.currentSource,actor:this.currentActor}),r.zIndex!==s.zIndex&&this.applyOperation({type:"setNodeZIndex",entity:"node",nodeId:e,zIndex:s.zIndex,previousZIndex:r.zIndex,timestamp:Date.now(),source:this.currentSource,actor:this.currentActor})}}i()},"set")})),this.nodeRefs.set(e,t)),t}getNodesInBounds(e){return At(()=>{this.version;const t=[];for(const[n]of this.ynodes){const i=this.ynodes.get(n);if(i){const s=be(i);s&&Ki(s.bounds,e)&&t.push(n)}}return t})}getAllNodes(){return At(()=>{this.version;const e=new Map;for(const[t]of this.ynodes){const n=this.ynodes.get(t);if(n){const i=be(n);i&&e.set(t,i)}}return e})}getVersion(){return At(()=>this.version)}queryNodeAtPoint(e){const t=[];for(const[n]of this.ynodes){const i=this.ynodes.get(n);if(i){const s=be(i);s&&t.push([n,s])}}t.sort(([,n],[,i])=>i.zIndex-n.zIndex);for(const[n,i]of t)if(Pt(e,i.bounds))return n;return null}queryNodesInBounds(e){return this.spatialIndex.query(e)}updateLinkLayout(e,t){const n=this.linkLayouts.get(e);if(n&&st(n.bounds,t.bounds)&&it(n.centerPos,t.centerPos)){t.path&&(n.path=t.path);return}this.linkLayouts.set(e,t)}deleteLinkLayout(e){if(this.linkLayouts.delete(e)){const t=[];for(const[n]of this.linkSegmentLayouts)n.startsWith(`${e}:`)&&t.push(n);for(const n of t)this.linkSegmentLayouts.delete(n),this.linkSegmentSpatialIndex.remove(n)}}updateSlotLayout(e,t){const n=this.slotLayouts.get(e);if(n){if(it(n.position,t.position)&&st(n.bounds,t.bounds))return;this.slotSpatialIndex.update(e,t.bounds)}else this.slotSpatialIndex.insert(e,t.bounds);this.slotLayouts.set(e,t)}batchUpdateSlotLayouts(e){if(e.length)for(const{key:t,layout:n}of e){const i=this.slotLayouts.get(t);if(i){if(it(i.position,n.position)&&st(i.bounds,n.bounds))continue;this.slotSpatialIndex.update(t,n.bounds)}else this.slotSpatialIndex.insert(t,n.bounds);this.slotLayouts.set(t,n)}}deleteSlotLayout(e){this.slotLayouts.delete(e)&&this.slotSpatialIndex.remove(e)}deleteNodeSlotLayouts(e){const t=[];for(const[n,i]of this.slotLayouts)i.nodeId===e&&t.push(n);for(const n of t)this.slotLayouts.delete(n),this.slotSpatialIndex.remove(n)}clearAllSlotLayouts(){this.slotLayouts.clear(),this.slotSpatialIndex.clear()}updateRerouteLayout(e,t){const n=this.rerouteLayouts.get(e);n||Re.debug("Adding reroute layout:",{rerouteId:e,position:t.position,bounds:t.bounds}),n?this.rerouteSpatialIndex.update(String(e),t.bounds):this.rerouteSpatialIndex.insert(String(e),t.bounds),this.rerouteLayouts.set(e,t)}deleteRerouteLayout(e){this.rerouteLayouts.delete(e)&&this.rerouteSpatialIndex.remove(String(e))}getLinkLayout(e){return this.linkLayouts.get(e)||null}getSlotLayout(e){return this.slotLayouts.get(e)||null}getRerouteLayout(e){return this.rerouteLayouts.get(e)||null}getAllSlotKeys(){return Array.from(this.slotLayouts.keys())}updateLinkSegmentLayout(e,t,n){const i=ho(e,t),s=this.linkSegmentLayouts.get(i);if(s&&st(s.bounds,n.bounds)&&it(s.centerPos,n.centerPos)){n.path&&(s.path=n.path);return}const a={...n,linkId:e,rerouteId:t};s||Re.debug("Adding link segment:",{linkId:e,rerouteId:t,bounds:n.bounds,hasPath:!!n.path}),s?this.linkSegmentSpatialIndex.update(i,n.bounds):this.linkSegmentSpatialIndex.insert(i,n.bounds),this.linkSegmentLayouts.set(i,a)}deleteLinkSegmentLayout(e,t){const n=ho(e,t);this.linkSegmentLayouts.delete(n)&&this.linkSegmentSpatialIndex.remove(n)}queryLinkSegmentAtPoint(e,t){const n=t?.lineWidth??10,i=Math.max(10,n),s={x:e.x-i,y:e.y-i,width:i*2,height:i*2},a=this.linkSegmentSpatialIndex.query(s);a.length>0&&Re.debug("Checking link segments at point:",{point:e,candidateCount:a.length,tolerance:n});for(const r of a){const l=this.linkSegmentLayouts.get(r);if(l){if(t&&l.path){const d=typeof window<"u"&&window?.devicePixelRatio||1;if(t.isPointInStroke(l.path,e.x*d,e.y*d))return Re.debug("Link segment hit:",{linkId:l.linkId,rerouteId:l.rerouteId,point:e}),{linkId:l.linkId,rerouteId:l.rerouteId}}else if(Pt(e,l.bounds))return{linkId:l.linkId,rerouteId:l.rerouteId}}}return null}queryLinkAtPoint(e,t){const n=this.queryLinkSegmentAtPoint(e,t);return n?n.linkId:null}querySlotAtPoint(e){const t={x:e.x-10,y:e.y-10,width:20,height:20},n=this.slotSpatialIndex.query(t);for(const i of n){const s=this.slotLayouts.get(i);if(s&&Pt(e,s.bounds))return s}return null}queryRerouteAtPoint(e){const n={x:e.x-20,y:e.y-20,width:40,height:40},i=this.rerouteSpatialIndex.query(n);i.length>0&&Re.debug("Checking reroutes at point:",{point:e,candidateCount:i.length});for(const s of i){const a=Mt(s),r=this.rerouteLayouts.get(a);if(r){const l=e.x-r.position.x,d=e.y-r.position.y,u=Math.sqrt(l*l+d*d);if(u<=r.radius)return Re.debug("Reroute hit:",{rerouteId:r.id,position:r.position,distance:u}),r}}return null}queryItemsInBounds(e){const t=this.linkSegmentSpatialIndex.query(e),n=new Set;for(const i of t){const s=this.linkSegmentLayouts.get(i);s&&n.add(s.linkId)}return{nodes:this.queryNodesInBounds(e),links:Array.from(n),slots:this.slotSpatialIndex.query(e),reroutes:this.rerouteSpatialIndex.query(e).map(i=>Mt(i))}}applyOperation(e){const t={type:"update",nodeIds:[],timestamp:e.timestamp,source:e.source,operation:e};this.ydoc.transact(()=>{this.yoperations.push([e]),this.applyOperationInTransaction(e,t)},this.currentActor),this.finalizeOperation(t)}applyOperationInTransaction(e,t){switch(e.type){case"moveNode":this.handleMoveNode(e,t);break;case"resizeNode":this.handleResizeNode(e,t);break;case"setNodeZIndex":this.handleSetNodeZIndex(e,t);break;case"createNode":this.handleCreateNode(e,t);break;case"deleteNode":this.handleDeleteNode(e,t);break;case"batchUpdateBounds":this.handleBatchUpdateBounds(e,t);break;case"createLink":this.handleCreateLink(e,t);break;case"deleteLink":this.handleDeleteLink(e,t);break;case"createReroute":this.handleCreateReroute(e,t);break;case"deleteReroute":this.handleDeleteReroute(e,t);break;case"moveReroute":this.handleMoveReroute(e,t);break}}finalizeOperation(e){this.version++,e.nodeIds.forEach(t=>{const n=this.nodeTriggers.get(t);n&&n()}),setTimeout(()=>this.notifyChange(e),0)}onChange(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}setSource(e){this.currentSource=e}setActor(e){this.currentActor=e}getCurrentSource(){return this.currentSource}getCurrentActor(){return this.currentActor}cleanupNodeRef(e){this.nodeRefs.delete(e),this.nodeTriggers.delete(e)}initializeFromLiteGraph(e){this.ydoc.transact(()=>{this.ynodes.clear(),this.spatialIndex.clear(),this.linkSegmentSpatialIndex.clear(),this.slotSpatialIndex.clear(),this.rerouteSpatialIndex.clear(),this.linkLayouts.clear(),this.linkSegmentLayouts.clear(),this.slotLayouts.clear(),this.rerouteLayouts.clear(),e.forEach((t,n)=>{const i={id:t.id.toString(),position:{x:t.pos[0],y:t.pos[1]},size:{width:t.size[0],height:t.size[1]},zIndex:n,visible:!0,bounds:{x:t.pos[0],y:t.pos[1],width:t.size[0],height:t.size[1]}};this.ynodes.set(i.id,go(i)),this.spatialIndex.insert(i.id,i.bounds)}),this.nodeTriggers.forEach(t=>t())},"initialization")}handleMoveNode(e,t){const n=this.ynodes.get(e.nodeId);if(!n)return;const i=be(n).size,s={x:e.position.x,y:e.position.y,width:i.width,height:i.height};this.spatialIndex.update(e.nodeId,s),n.set("position",e.position),this.updateNodeBounds(n,e.position,i),t.nodeIds.push(e.nodeId)}handleResizeNode(e,t){const n=this.ynodes.get(e.nodeId);if(!n)return;const i=be(n).position,s={x:i.x,y:i.y,width:e.size.width,height:e.size.height};this.spatialIndex.update(e.nodeId,s),n.set("size",e.size),this.updateNodeBounds(n,i,e.size),t.nodeIds.push(e.nodeId)}handleSetNodeZIndex(e,t){const n=this.ynodes.get(e.nodeId);n&&(n.set("zIndex",e.zIndex),t.nodeIds.push(e.nodeId))}handleCreateNode(e,t){const n=go(e.layout);this.ynodes.set(e.nodeId,n),this.spatialIndex.insert(e.nodeId,e.layout.bounds),t.type="create",t.nodeIds.push(e.nodeId)}handleDeleteNode(e,t){if(!this.ynodes.has(e.nodeId))return;this.ynodes.delete(e.nodeId),this.spatialIndex.remove(e.nodeId),this.deleteNodeSlotLayouts(e.nodeId);const n=this.findLinksConnectedToNode(e.nodeId);for(const i of n)this.ylinks.delete(String(i)),this.linkLayouts.delete(i),this.cleanupLinkSegments(i);t.type="delete",t.nodeIds.push(e.nodeId)}handleBatchUpdateBounds(e,t){const n=[];for(const i of e.nodeIds){const s=e.bounds[i],a=this.ynodes.get(i);!a||!s||(a.set("position",{x:s.bounds.x,y:s.bounds.y}),a.set("size",{width:s.bounds.width,height:s.bounds.height}),a.set("bounds",s.bounds),n.push({nodeId:i,bounds:s.bounds}),t.nodeIds.push(i))}n.length>0&&this.spatialIndex.batchUpdate(n),t.nodeIds.length&&(t.type="update")}handleCreateLink(e,t){const n=new qt;n.set("id",e.linkId),n.set("sourceNodeId",e.sourceNodeId),n.set("sourceSlot",e.sourceSlot),n.set("targetNodeId",e.targetNodeId),n.set("targetSlot",e.targetSlot),this.ylinks.set(String(e.linkId),n),t.type="create"}handleDeleteLink(e,t){this.ylinks.has(String(e.linkId))&&(this.ylinks.delete(String(e.linkId)),this.linkLayouts.delete(e.linkId),this.cleanupLinkSegments(e.linkId),t.type="delete")}handleCreateReroute(e,t){const n=new qt;n.set("id",e.rerouteId),n.set("position",e.position),n.set("parentId",e.parentId),n.set("linkIds",e.linkIds),this.yreroutes.set(String(e.rerouteId),n),t.type="create"}handleDeleteReroute(e,t){this.yreroutes.has(String(e.rerouteId))&&(this.yreroutes.delete(String(e.rerouteId)),this.rerouteLayouts.delete(e.rerouteId),this.rerouteSpatialIndex.remove(String(e.rerouteId)),t.type="delete")}handleMoveReroute(e,t){const n=this.yreroutes.get(String(e.rerouteId));if(!n)return;n.set("position",e.position);const i=e.position,s={id:e.rerouteId,position:i,radius:8,bounds:{x:i.x-8,y:i.y-8,width:16,height:16}};this.updateRerouteLayout(e.rerouteId,s),t.type="update"}updateNodeBounds(e,t,n){e.set("bounds",{x:t.x,y:t.y,width:n.width,height:n.height})}findLinksConnectedToNode(e){const t=[];return this.ylinks.forEach((n,i)=>{const s=_o(i),a=this.getLinkField(n,"sourceNodeId"),r=this.getLinkField(n,"targetNodeId");(a===e||r===e)&&t.push(s)}),t}handleLinkChange(e,t){if(e.action==="delete"){const n=_o(t);this.cleanupLinkData(n)}}cleanupLinkData(e){this.linkLayouts.delete(e),this.cleanupLinkSegments(e)}cleanupLinkSegments(e){const t=[];for(const[n]of this.linkSegmentLayouts)n.startsWith(`${e}:`)&&t.push(n);for(const n of t)this.linkSegmentLayouts.delete(n),this.linkSegmentSpatialIndex.remove(n)}handleRerouteChange(e,t){const n=Mt(t);e.action==="delete"?this.handleRerouteDelete(n):this.handleRerouteUpsert(n)}handleRerouteDelete(e){this.rerouteLayouts.delete(e),this.rerouteSpatialIndex.remove(String(e))}handleRerouteUpsert(e){const t=this.yreroutes.get(String(e));if(!t)return;const n=this.getRerouteField(t,"position");if(!n)return;const i=this.createRerouteLayout(e,n);this.updateRerouteLayout(e,i)}createRerouteLayout(e,t){return{id:e,position:t,radius:8,bounds:{x:t.x-8,y:t.y-8,width:16,height:16}}}notifyChange(e){this.changeListeners.forEach(t=>{try{t(e)}catch(n){console.error("Error in layout change listener:",n)}})}getOperationsSince(e){const t=[];return this.yoperations.forEach(n=>{n&&n.timestamp>e&&t.push(n)}),t}getOperationsByActor(e){const t=[];return this.yoperations.forEach(n=>{n&&n.actor===e&&t.push(n)}),t}getYDoc(){return this.ydoc}applyUpdate(e){Qn(this.ydoc,e)}getStateAsUpdate(){return ei(this.ydoc)}batchUpdateNodeBounds(e){if(e.length===0)return;const t=this.currentSource,n=t===ue.DOM;this.currentSource=ue.Vue;const i=[],s={};for(const{nodeId:r,bounds:l}of e){const d=this.ynodes.get(r);if(!d)continue;const u=be(d);s[r]={bounds:n?{...l,height:on(l.height)}:l,previousBounds:u.bounds},i.push(r)}if(!i.length){this.currentSource=t;return}const a={type:"batchUpdateBounds",entity:"node",nodeIds:i,bounds:s,timestamp:Date.now(),source:this.currentSource,actor:this.currentActor};this.applyOperation(a),this.currentSource=t}};const D=new Yi;var je=nn.default.getLogger("LayoutMutations");function Ae(){const o=h(g=>{D.setSource(g)},"setSource"),e=h(g=>{D.setActor(g)},"setActor"),t=h((g,f)=>{const y=String(g),b=D.getNodeLayoutRef(y).value;b&&D.applyOperation({type:"moveNode",entity:"node",nodeId:y,position:f,previousPosition:b.position,timestamp:Date.now(),source:D.getCurrentSource(),actor:D.getCurrentActor()})},"moveNode"),n=h((g,f)=>{const y=String(g),b=D.getNodeLayoutRef(y).value;b&&D.applyOperation({type:"resizeNode",entity:"node",nodeId:y,size:f,previousSize:b.size,timestamp:Date.now(),source:D.getCurrentSource(),actor:D.getCurrentActor()})},"resizeNode"),i=h((g,f)=>{const y=String(g),b=D.getNodeLayoutRef(y).value;b&&D.applyOperation({type:"setNodeZIndex",entity:"node",nodeId:y,zIndex:f,previousZIndex:b.zIndex,timestamp:Date.now(),source:D.getCurrentSource(),actor:D.getCurrentActor()})},"setNodeZIndex");return{setSource:o,setActor:e,moveNode:t,resizeNode:n,setNodeZIndex:i,createNode:h((g,f)=>{const y=String(g),b={id:y,position:f.position??{x:0,y:0},size:f.size??{width:200,height:100},zIndex:f.zIndex??0,visible:f.visible??!0,bounds:{x:f.position?.x??0,y:f.position?.y??0,width:f.size?.width??200,height:f.size?.height??100}};D.applyOperation({type:"createNode",entity:"node",nodeId:y,layout:b,timestamp:Date.now(),source:D.getCurrentSource(),actor:D.getCurrentActor()})},"createNode"),deleteNode:h(g=>{const f=String(g),y=D.getNodeLayoutRef(f).value;y&&D.applyOperation({type:"deleteNode",entity:"node",nodeId:f,previousLayout:y,timestamp:Date.now(),source:D.getCurrentSource(),actor:D.getCurrentActor()})},"deleteNode"),bringNodeToFront:h(g=>{const f=D.getAllNodes().value;let y=0;for(const[,b]of f)b.zIndex>y&&(y=b.zIndex);i(g,y+1)},"bringNodeToFront"),createLink:h((g,f,y,b,v)=>{const k=String(f),w=String(b);je.debug("Creating link:",{linkId:g,from:`${k}[${y}]`,to:`${w}[${v}]`}),D.applyOperation({type:"createLink",entity:"link",linkId:g,sourceNodeId:k,sourceSlot:y,targetNodeId:w,targetSlot:v,timestamp:Date.now(),source:D.getCurrentSource(),actor:D.getCurrentActor()})},"createLink"),deleteLink:h(g=>{je.debug("Deleting link:",g),D.applyOperation({type:"deleteLink",entity:"link",linkId:g,timestamp:Date.now(),source:D.getCurrentSource(),actor:D.getCurrentActor()})},"deleteLink"),createReroute:h((g,f,y,b=[])=>{je.debug("Creating reroute:",{rerouteId:g,position:f,parentId:y,linkCount:b.length}),D.applyOperation({type:"createReroute",entity:"reroute",rerouteId:g,position:f,parentId:y,linkIds:b,timestamp:Date.now(),source:D.getCurrentSource(),actor:D.getCurrentActor()})},"createReroute"),deleteReroute:h(g=>{je.debug("Deleting reroute:",g),D.applyOperation({type:"deleteReroute",entity:"reroute",rerouteId:g,timestamp:Date.now(),source:D.getCurrentSource(),actor:D.getCurrentActor()})},"deleteReroute"),moveReroute:h((g,f,y)=>{je.debug("Moving reroute:",{rerouteId:g,from:y,to:f}),D.applyOperation({type:"moveReroute",entity:"reroute",rerouteId:g,position:f,previousPosition:y,timestamp:Date.now(),source:D.getCurrentSource(),actor:D.getCurrentActor()})},"moveReroute")}}h(Ae,"useLayoutMutations");const NS="workflow",xS=">";var Qi=class{static{h(this,"CanvasPathRenderer")}drawLink(o,e,t){const n=new Path2D,i=t.highlightedIds?.has(e.id)??!1,s=this.determineLinkColor(e,t,i);return o.save(),e.disabled&&t.patterns?.disabled?o.strokeStyle=t.patterns.disabled:o.strokeStyle=s,o.lineWidth=t.style.connectionWidth,o.lineJoin="round",t.style.borderWidth&&!t.style.lowQuality&&this.drawLinkPath(o,n,e,t,t.style.connectionWidth+t.style.borderWidth,"rgba(0,0,0,0.5)"),this.drawLinkPath(o,n,e,t,t.style.connectionWidth,s),this.calculateCenterPoint(e,t),t.style.showArrows&&this.drawArrows(o,e,t,s),t.style.showCenterMarker&&t.scale&&t.scale>=.6&&t.style.highQuality&&this.drawCenterMarker(o,e,t,s),e.flow&&t.animation&&this.drawFlowAnimation(o,n,e,t),o.restore(),n}determineLinkColor(o,e,t){return t?e.colors.highlighted:o.color?o.color:o.type&&e.colors.byType[o.type]?e.colors.byType[o.type]:e.colors.default}drawLinkPath(o,e,t,n,i,s){o.strokeStyle=s,o.lineWidth=i;const a=t.startPoint,r=t.endPoint;n.style.mode==="linear"?this.buildLinearPath(e,a,r,t.startDirection,t.endDirection):n.style.mode==="straight"?this.buildStraightPath(e,a,r,t.startDirection,t.endDirection):this.buildSplinePath(e,a,r,t.startDirection,t.endDirection,t.controlPoints),o.stroke(e)}buildLinearPath(o,e,t,n,i){const a={x:e.x,y:e.y},r={x:t.x,y:t.y};switch(n){case"left":a.x-=15;break;case"right":a.x+=15;break;case"up":a.y-=15;break;case"down":a.y+=15;break;case"none":break}switch(i){case"left":r.x-=15;break;case"right":r.x+=15;break;case"up":r.y-=15;break;case"down":r.y+=15;break;case"none":break}o.moveTo(e.x,e.y),o.lineTo(a.x,a.y),o.lineTo(r.x,r.y),o.lineTo(t.x,t.y)}buildStraightPath(o,e,t,n,i){const a={x:e.x,y:e.y},r={x:t.x,y:t.y};switch(n){case"left":a.x-=10;break;case"right":a.x+=10;break;case"up":a.y-=10;break;case"down":a.y+=10;break;case"none":break}switch(i){case"left":r.x-=10;break;case"right":r.x+=10;break;case"up":r.y-=10;break;case"down":r.y+=10;break;case"none":break}const l=(a.x+r.x)*.5;o.moveTo(e.x,e.y),o.lineTo(a.x,a.y),o.lineTo(l,a.y),o.lineTo(l,r.y),o.lineTo(r.x,r.y),o.lineTo(t.x,t.y)}buildSplinePath(o,e,t,n,i,s){o.moveTo(e.x,e.y);const a=s||this.calculateControlPoints(e,t,n,i);a.length>=2?o.bezierCurveTo(a[0].x,a[0].y,a[1].x,a[1].y,t.x,t.y):a.length===1?o.quadraticCurveTo(a[0].x,a[0].y,t.x,t.y):o.lineTo(t.x,t.y)}calculateControlPoints(o,e,t,n){const i=Math.sqrt(Math.pow(e.x-o.x,2)+Math.pow(e.y-o.y,2)),s=Math.max(30,i*.25),a=this.getDirectionOffset(t,s),r=this.getDirectionOffset(n,s);return[{x:o.x+a.x,y:o.y+a.y},{x:e.x+r.x,y:e.y+r.y}]}getDirectionOffset(o,e){switch(o){case"left":return{x:-e,y:0};case"right":return{x:e,y:0};case"up":return{x:0,y:-e};case"down":return{x:0,y:e};case"none":default:return{x:0,y:0}}}drawArrows(o,e,t,n){if(t.style.showArrows)for(const i of[.25,.75]){const s=this.computeConnectionPoint(e,i,t),a=this.computeConnectionPoint(e,i+.01,t),r=Math.atan2(a.y-s.y,a.x-s.x),l=o.getTransform();o.translate(s.x,s.y),o.rotate(r),o.fillStyle=n,o.beginPath(),o.moveTo(-5,-3),o.lineTo(0,7),o.lineTo(5,-3),o.fill(),o.setTransform(l)}}computeConnectionPoint(o,e,t){const{startPoint:n,endPoint:i,startDirection:s,endDirection:a}=o,r=Math.sqrt(Math.pow(i.x-n.x,2)+Math.pow(i.y-n.y,2)),l=.25,d={x:n.x,y:n.y},u={x:i.x,y:i.y};switch(s){case"left":d.x-=r*l;break;case"right":d.x+=r*l;break;case"up":d.y-=r*l;break;case"down":d.y+=r*l;break;case"none":break}switch(a){case"left":u.x-=r*l;break;case"right":u.x+=r*l;break;case"up":u.y-=r*l;break;case"down":u.y+=r*l;break;case"none":break}const p=(1-e)*(1-e)*(1-e),m=3*((1-e)*(1-e))*e,g=3*(1-e)*(e*e),f=e*e*e;return{x:p*n.x+m*d.x+g*u.x+f*i.x,y:p*n.y+m*d.y+g*u.y+f*i.y}}drawFlowAnimation(o,e,t,n){if(!n.animation)return;const i=n.animation.time,s=this.determineLinkColor(t,n,!1);o.save(),o.fillStyle=s;for(let a=0;a<5;++a){const r=(i+a*.2)%1,l=this.computeConnectionPoint(t,r,n);o.beginPath(),o.arc(l.x,l.y,5,0,2*Math.PI),o.fill()}o.restore()}findPointOnBezier(o,e,t,n,i){const s=1-o,a=s*s,r=a*s,l=o*o,d=l*o;return{x:r*e.x+3*a*o*t.x+3*s*l*n.x+d*i.x,y:r*e.y+3*a*o*t.y+3*s*l*n.y+d*i.y}}drawDraggingLink(o,e,t){const n=e.fromInput?{id:"dragging",startPoint:e.dragPoint,endPoint:e.fixedPoint,startDirection:e.dragDirection||this.getOppositeDirection(e.fixedDirection),endDirection:e.fixedDirection,color:e.color,type:e.type,disabled:e.disabled}:{id:"dragging",startPoint:e.fixedPoint,endPoint:e.dragPoint,startDirection:e.fixedDirection,endDirection:e.dragDirection||this.getOppositeDirection(e.fixedDirection),color:e.color,type:e.type,disabled:e.disabled};return this.drawLink(o,n,t)}getOppositeDirection(o){switch(o){case"left":return"right";case"right":return"left";case"up":return"down";case"down":return"up";case"none":default:return"none"}}getLinkCenter(o){return{x:(o.startPoint.x+o.endPoint.x)/2,y:(o.startPoint.y+o.endPoint.y)/2}}calculateCenterPoint(o,e){const{startPoint:t,endPoint:n,controlPoints:i}=o;if(e.style.mode==="spline"&&i&&i.length>=2){const s=this.findPointOnBezier(.5,t,i[0],i[1],n);if(o.centerPos=s,e.style.centerMarkerShape==="arrow"){const a=this.findPointOnBezier(.51,t,i[0],i[1],n);o.centerAngle=Math.atan2(a.y-s.y,a.x-s.x)}}else if(e.style.mode==="linear"){const a={x:t.x,y:t.y},r={x:n.x,y:n.y};switch(o.startDirection){case"left":a.x-=15;break;case"right":a.x+=15;break;case"up":a.y-=15;break;case"down":a.y+=15;break}switch(o.endDirection){case"left":r.x-=15;break;case"right":r.x+=15;break;case"up":r.y-=15;break;case"down":r.y+=15;break}o.centerPos={x:(a.x+r.x)*.5,y:(a.y+r.y)*.5},e.style.centerMarkerShape==="arrow"&&(o.centerAngle=Math.atan2(r.y-a.y,r.x-a.x))}else if(e.style.mode==="straight"){const a={x:t.x,y:t.y},r={x:n.x,y:n.y};switch(o.startDirection){case"left":a.x-=10;break;case"right":a.x+=10;break;case"up":a.y-=10;break;case"down":a.y+=10;break}switch(o.endDirection){case"left":r.x-=10;break;case"right":r.x+=10;break;case"up":r.y-=10;break;case"down":r.y+=10;break}if(o.centerPos={x:(a.x+r.x)*.5,y:(a.y+r.y)*.5},e.style.centerMarkerShape==="arrow"){const l=r.y-a.y;Math.abs(l)<4?o.centerAngle=0:l>0?o.centerAngle=Math.PI*.5:o.centerAngle=-(Math.PI*.5)}}else o.centerPos=this.getLinkCenter(o),e.style.centerMarkerShape==="arrow"&&(o.centerAngle=Math.atan2(n.y-t.y,n.x-t.x))}drawCenterMarker(o,e,t,n){if(e.centerPos){if(o.beginPath(),t.style.centerMarkerShape==="arrow"&&e.centerAngle!==void 0){const i=o.getTransform();o.translate(e.centerPos.x,e.centerPos.y),o.rotate(e.centerAngle),o.moveTo(-3.2,-5),o.lineTo(7,0),o.lineTo(-3.2,5),o.setTransform(i)}else o.arc(e.centerPos.x,e.centerPos.y,5,0,Math.PI*2);if(e.disabled&&t.patterns?.disabled){const{fillStyle:i,globalAlpha:s}=o;o.fillStyle=t.patterns.disabled,o.globalAlpha=.75,o.fill(),o.globalAlpha=s,o.fillStyle=i}else o.fillStyle=n,o.fill()}}},yo=class{static{h(this,"LitegraphLinkAdapter")}pathRenderer=new Qi;constructor(o=!0){this.enableLayoutStoreWrites=o}convertDirection(o){switch(o){case O.LEFT:return"left";case O.RIGHT:return"right";case O.UP:return"up";case O.DOWN:return"down";case O.CENTER:return"none";default:return"right"}}convertToPathRenderContext(o){const e=o.scale>=.6&&o.highQualityRender&&o.renderConnectionArrows,t=o.linkMarkerShape!==re.None;return{style:{mode:this.convertRenderMode(o.renderMode),connectionWidth:o.connectionWidth,borderWidth:o.renderBorder?4:void 0,arrowShape:this.convertArrowShape(o.linkMarkerShape),showArrows:e,lowQuality:o.lowQuality,showCenterMarker:t,centerMarkerShape:o.linkMarkerShape===re.Arrow?"arrow":"circle",highQuality:o.highQualityRender},colors:{default:String(o.defaultLinkColor),byType:this.convertColorMap(o.linkTypeColors),highlighted:"#FFF"},patterns:{disabled:o.disabledPattern},animation:{time:_.getTime()*.001},scale:o.scale,highlightedIds:new Set(Array.from(o.highlightedLinks).map(String))}}convertRenderMode(o){switch(o){case ie.LINEAR_LINK:return"linear";case ie.STRAIGHT_LINK:return"straight";case ie.SPLINE_LINK:default:return"spline"}}convertArrowShape(o){switch(o){case re.Circle:return"circle";case re.Arrow:default:return"triangle"}}convertColorMap(o){const e={};for(const[t,n]of Object.entries(o))e[t]=String(n);return e}applySplineOffset(o,e,t){switch(e){case O.LEFT:o.x-=t;break;case O.RIGHT:o.x+=t;break;case O.UP:o.y-=t;break;case O.DOWN:o.y+=t;break}}renderLinkDirect(o,e,t,n,i,s,a,r,l,d,u={}){const p=r||O.RIGHT,m=l||O.LEFT,g=s===!0||typeof s=="number"&&s>0,f={id:n?String(n.id):"temp",startPoint:{x:e[0],y:e[1]},endPoint:{x:t[0],y:t[1]},startDirection:this.convertDirection(p),endDirection:this.convertDirection(m),color:a!=null?String(a):void 0,type:n?.type!==void 0?String(n.type):void 0,flow:g,disabled:u.disabled||!1};if(d.renderMode===ie.SPLINE_LINK){const k=!!u.startControl,w=!!u.endControl,S=Math.sqrt((t[0]-e[0])*(t[0]-e[0])+(t[1]-e[1])*(t[1]-e[1])),E=.25,C=[];if(k&&w)C.push({x:e[0]+(u.startControl[0]||0),y:e[1]+(u.startControl[1]||0)},{x:t[0]+(u.endControl[0]||0),y:t[1]+(u.endControl[1]||0)}),f.controlPoints=C;else if(k&&!w){const I={x:e[0]+(u.startControl[0]||0),y:e[1]+(u.startControl[1]||0)},P={x:t[0],y:t[1]};this.applySplineOffset(P,m,S*E),C.push(I,P),f.controlPoints=C}else if(!k&&w){const I={x:e[0],y:e[1]};this.applySplineOffset(I,p,S*E);const P={x:t[0]+(u.endControl[0]||0),y:t[1]+(u.endControl[1]||0)};C.push(I,P),f.controlPoints=C}else{const I={x:e[0],y:e[1]},P={x:t[0],y:t[1]};this.applySplineOffset(I,p,S*E),this.applySplineOffset(P,m,S*E),C.push(I,P),f.controlPoints=C}}const y=this.convertToPathRenderContext(d);i&&(y.style.borderWidth=void 0);const b=this.pathRenderer.drawLink(o,f,y),v=u.reroute??n;if(v&&(v.path=b,f.centerPos&&(v._pos=v._pos||[0,0],v._pos[0]=f.centerPos.x,v._pos[1]=f.centerPos.y,f.centerAngle!==void 0&&(v._centreAngle=f.centerAngle)),this.enableLayoutStoreWrites&&n&&n.id!==-1)){const k=this.calculateLinkBounds([f.startPoint.x,f.startPoint.y],[f.endPoint.x,f.endPoint.y],f),w=f.centerPos||{x:(f.startPoint.x+f.endPoint.x)/2,y:(f.startPoint.y+f.endPoint.y)/2};u.reroute||D.updateLinkLayout(n.id,{id:n.id,path:b,bounds:k,centerPos:w,sourceNodeId:String(n.origin_id),targetNodeId:String(n.target_id),sourceSlot:n.origin_slot,targetSlot:n.target_slot});const S=u.reroute?u.reroute.id:null;D.updateLinkSegmentLayout(n.id,S,{path:b,bounds:k,centerPos:w})}}renderDraggingLink(o,e,t,n,i,s,a){this.renderLinkDirect(o,e,t,null,!1,null,n,i,s,{...a,linkMarkerShape:re.None},{disabled:!1})}calculateLinkBounds(o,e,t){let n=Math.min(o[0],e[0]),i=Math.max(o[0],e[0]),s=Math.min(o[1],e[1]),a=Math.max(o[1],e[1]);if(t.controlPoints)for(const l of t.controlPoints)n=Math.min(n,l.x),i=Math.max(i,l.x),s=Math.min(s,l.y),a=Math.max(a,l.y);const r=20;return{x:n-r,y:s-r,width:i-n+2*r,height:a-s+2*r}}};function an(o){const{color_off:e,color_on:t,dir:n,label:i,localized_name:s,locked:a,name:r,nameLocked:l,removable:d,shape:u,type:p}=o;return{color_off:e,color_on:t,dir:n,label:i,localized_name:s,locked:a,name:r,nameLocked:l,removable:d,shape:u,type:p}}h(an,"shallowCloneCommonProps");function Zi(o){const{link:e}=o,t=o.widget?{widget:{name:o.widget.name}}:{pos:o.pos};return{...an(o),...t,link:e}}h(Zi,"inputAsSerialisable");function Ji(o){const{pos:e,slot_index:t,links:n,widget:i}=o,s=i?{widget:{name:i.name}}:null;return{...an(o),...s,pos:e,slot_index:t,links:n}}h(Ji,"outputAsSerialisable");function es(o){return"link"in o}h(es,"isINodeInputSlot");function we(o){return!!o.widget}h(we,"isWidgetInputSlot");function ts(o,e,t){if(typeof o=="object"){const{nodeId:n,index:i,isInput:s}=o;return`${n}-${s?"in":"out"}-${i}`}if(e===void 0||t===void 0)throw new Error("Missing required parameters for slot key generation");return`${o}-${t?"in":"out"}-${e}`}h(ts,"getSlotKey");function bo(o,e){const t=o.inputs[e];return t?rn(o,t):[o.nodeX,o.nodeY]}h(bo,"calculateInputSlotPos");function rn(o,e){const{nodeX:t,nodeY:n,collapsed:i}=o;if(i)return[t,n-_.NODE_TITLE_HEIGHT*.5];const{pos:s}=e;if(s)return[t+s[0],n+s[1]];const a=_.NODE_SLOT_HEIGHT*.5,r=o.slotStartY||0,l=(os(o).indexOf(e)+.7)*_.NODE_SLOT_HEIGHT;return[t+a,n+l+r]}h(rn,"calculateInputSlotPosFromSlot");function vo(o,e){const{nodeX:t,nodeY:n,nodeWidth:i,collapsed:s,collapsedWidth:a,outputs:r}=o;if(s){const g=a||_.NODE_COLLAPSED_WIDTH,f=_.NODE_TITLE_HEIGHT*.5;return[t+g,n-f]}const l=r[e];if(!l)return[t+i,n];const d=l.pos;if(d)return[t+d[0],n+d[1]];const u=_.NODE_SLOT_HEIGHT*.5,p=o.slotStartY||0,m=(ns(o).indexOf(l)+.7)*_.NODE_SLOT_HEIGHT;return[t+i+1-u,n+m+p]}h(vo,"calculateOutputSlotPos");function ae(o,e,t){if(_.vueNodesMode){const i=ts(String(o.id),e,t),s=D.getSlotLayout(i);if(s)return[s.position.x,s.position.y];const a=D.getNodeLayoutRef(String(o.id)).value;if(a){const r={nodeX:a.position.x,nodeY:a.position.y,nodeWidth:a.size.width,nodeHeight:a.size.height,collapsed:o.flags.collapsed||!1,collapsedWidth:o._collapsed_width,slotStartY:o.constructor.slot_start_y,inputs:o.inputs,outputs:o.outputs,widgets:o.widgets};return t?bo(r,e):vo(r,e)}}const n={nodeX:o.pos[0],nodeY:o.pos[1],nodeWidth:o.size[0],nodeHeight:o.size[1],collapsed:o.flags.collapsed||!1,collapsedWidth:o._collapsed_width,slotStartY:o.constructor.slot_start_y,inputs:o.inputs,outputs:o.outputs,widgets:o.widgets};return t?bo(n,e):vo(n,e)}h(ae,"getSlotPosition");function os(o){return o.inputs.filter(e=>!e.pos&&!(o.widgets?.length&&we(e)))}h(os,"getDefaultVerticalInputs");function ns(o){return o.outputs.filter(e=>!e.pos)}h(ns,"getDefaultVerticalOutputs");function is(o){if(typeof o!="string")return!1;const e=o.split(":");return e.length===1?o.length>0:e.length!==2||!e[1]?!1:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e[0])}h(is,"isNodeLocatorId");function ss(o){return typeof o!="string"?!1:o.includes(":")}h(ss,"isNodeExecutionId");function as(o){if(!is(o))return null;const e=o.split(":");if(e.length===1)return{subgraphUuid:null,localNodeId:isNaN(Number(o))?o:Number(o)};const[t,n]=e;return{subgraphUuid:t,localNodeId:isNaN(Number(n))?n:Number(n)}}h(as,"parseNodeLocatorId");function AS(o,e){return`${o}:${e}`}h(AS,"createNodeLocatorId");function DS(o){return ss(o)?o.split(":").map(e=>isNaN(Number(e))?e:Number(e)):null}h(DS,"parseNodeExecutionId");function OS(o){return o.join(":")}h(OS,"createNodeExecutionId");const PS=h(o=>o instanceof DOMException&&o.name==="AbortError","isAbortError"),MS=h(o=>o?.isRootGraph===!1,"isSubgraph"),RS=h(o=>o!=null,"isNonNullish"),rs=h(o=>{const e=o.constructor?.comfyClass;return e==="SubgraphInputNode"||e==="SubgraphOutputNode"},"isSubgraphIoNode"),FS=h(o=>o!==null&&typeof o=="object"&&"name"in o&&"type"in o&&"boundingRect"in o,"isSlotObject"),zS=h(o=>o==="input"||o==="output"||o==="temp","isResultItemType");function BS(o){return o.subgraphId?`${o.subgraphId}:${String(o.id)}`:String(o.id)}h(BS,"getLocatorIdFromNodeData");function ln(o){return!o||typeof o!="string"?null:o.split(":").filter(e=>e.length>0)}h(ln,"parseExecutionId");function ls(o){const e=ln(o);return e?e[e.length-1]:null}h(ls,"getLocalNodeIdFromExecutionId");function ds(o){const e=ln(o);return e?e.slice(0,-1):[]}h(ds,"getSubgraphPathFromExecutionId");function dn(o,e){for(const t of o.nodes)e(t)}h(dn,"visitGraphNodes");function us(o,e){let t=o;for(const n of e){const i=t.getNodeById(n);if(!i?.isSubgraphNode?.()||!i.subgraph)return null;t=i.subgraph}return t}h(us,"traverseSubgraphPath");function VS(o,e){Ge(o,t=>{const n=t[e];typeof n=="function"&&n.call(t)})}h(VS,"triggerCallbackOnAllNodes");function un(o,e){const t=[];return dn(o,n=>{n.isSubgraphNode?.()&&n.subgraph&&t.push(...un(n.subgraph,e));const i=e(n);i!==void 0&&t.push(i)}),t}h(un,"mapAllNodes");function Ge(o,e){dn(o,t=>{t.isSubgraphNode?.()&&t.subgraph&&Ge(t.subgraph,e),e(t)})}h(Ge,"forEachNode");function US(o,e){return un(o,t=>{if(!e||e(t))return t})}h(US,"collectAllNodes");function cn(o,e){for(const t of o.nodes)if(t.isSubgraphNode?.()&&t.subgraph){if(t.subgraph.id===e)return t.subgraph;const n=cn(t.subgraph,e);if(n)return n}return null}h(cn,"findSubgraphByUuid");function WS(o,e){const t=[{graph:o,path:[]}];for(;t.length>0;){const{graph:n,path:i}=t.pop();if(!(!n||!n._nodes||!Array.isArray(n._nodes))){for(const s of n._nodes)if(s.isSubgraphNode?.()&&s.subgraph){const a=[...i,String(s.subgraph.id)];if(s.subgraph.id===e)return a;t.push({graph:s.subgraph,path:a})}}}return null}h(WS,"findSubgraphPathById");function GS(o,e){if(!o)return null;const t=ls(e);if(!t)return null;const n=ds(e);if(n.length===0)return o.getNodeById(t)||null;const i=us(o,n);return i&&i.getNodeById(t)||null}h(GS,"getNodeByExecutionId");function HS(o,e){if(!o)return null;const t=as(e);if(!t)return null;const{subgraphUuid:n,localNodeId:i}=t;if(!n)return o.getNodeById(i)||null;const s=cn(o,n);return s&&s.getNodeById(i)||null}h(HS,"getNodeByLocatorId");function jS(o,e,t){!o||!e||Ge(o,n=>{n.type===e&&t(n)})}h(jS,"forEachSubgraphNode");function qS(o){return o.nodes.filter(e=>!rs(e))}h(qS,"getAllNonIoNodesInSubgraph");function cs(o,e){const{visitor:t=h(()=>{},"visitor"),initialContext:n=void 0,expandSubgraphs:i=!0}=e||{},s=[];for(const a of o)s.push({node:a,context:n});for(;s.length>0;){const{node:a,context:r}=s.pop(),l=t(a,r);if(i&&a.isSubgraphNode?.()&&a.subgraph){const d=a.subgraph.nodes;for(let u=d.length-1;u>=0;u--)s.push({node:d[u],context:l})}}}h(cs,"traverseNodesDepthFirst");function $S(o,e,t){let n=t;return Ge(o,i=>{n=e(n,i)}),n}h($S,"reduceAllNodes");function ps(o,e){const{collector:t=h(r=>r,"collector"),contextBuilder:n=h(()=>{},"contextBuilder"),initialContext:i=void 0,expandSubgraphs:s=!0}=e||{},a=[];return cs(o,{visitor:h((r,l)=>{const d=t(r,l);return d!==null&&a.push(d),n(r,l)},"visitor"),initialContext:i,expandSubgraphs:s}),a}h(ps,"collectFromNodes");function KS(o,e=o[0]?.graph){if(!e)return[];const t=e.rootGraph,n=e.isRootGraph?"":pn(e,t);return n===void 0?[]:ps(o,{collector:h((i,s)=>{const a=String(i.id);return s?`${s}:${a}`:a},"collector"),contextBuilder:h((i,s)=>{const a=String(i.id);return s?`${s}:${a}`:a},"contextBuilder"),initialContext:n,expandSubgraphs:!0})}h(KS,"getExecutionIdsForSelectedNodes");function pn(o,e){for(const t of e.nodes){if(!t.isSubgraphNode())continue;if(t.subgraph===o)return`${t.id}`;const n=pn(o,t.subgraph);if(n!==void 0)return t.id+":"+n}}h(pn,"findPartialExecutionPathToGraph");var ms=class Se{static{h(this,"CanvasPointer")}static bufferTime=150;static doubleClickTime=300;static get maxClickDrift(){return this.#e}static set maxClickDrift(e){this.#e=e,this.#t=e*e}static#e=6;static#t=this.#e**2;static trackpadThreshold=60;static trackpadMaxGap=500;static maxHighResBufferTime=10;element;pointerId;dragStarted=!1;eLastDown;isDouble=!1;isDown=!1;resizeDirection;clearEventsOnReset=!0;eDown;eMove;eUp;detectedDevice="mouse";lastWheelEventTime=0;hasReceivedWheelEvent=!1;bufferedLinuxEvent;bufferedLinuxEventTime=0;linuxBufferTimeoutId;get finally(){return this.#o}set finally(e){try{this.#o?.()}finally{this.#o=e}}#o;constructor(e){this.element=e}down(e){this.reset(),this.eDown=e,this.pointerId=e.pointerId,this.element.setPointerCapture(e.pointerId)}move(e){const{eDown:t}=this;if(t){if(!e.buttons){this.reset();return}if(!(e.buttons&t.buttons)){this.#n(e),this.reset();return}this.eMove=e,this.onDrag?.(e),!this.dragStarted&&(e.timeStamp-t.timeStamp>Se.bufferTime||!this.#s(e,t))&&this.#d(e)}}up(e){if(e.button!==this.eDown?.button)return!1;this.#n(e);const{dragStarted:t}=this;return this.reset(),!t}#n(e){const{eDown:t}=this;t&&(this.eUp=e,this.dragStarted?this.onDragEnd?.(e):this.#s(e,t)?this.onDoubleClick&&this.#i()?(this.onDoubleClick(e),this.eLastDown=void 0):(this.onClick?.(e),this.eLastDown=t):(this.#d(),this.onDragEnd?.(e)))}#s(e,t,n=Se.#t){return Vi(e.clientX,e.clientY,t.clientX,t.clientY)<=n}#i(){const{eDown:e,eLastDown:t}=this;if(!e||!t)return!1;const n=(3*Se.#e)**2,i=e.timeStamp-t.timeStamp;return i>0&&i<Se.doubleClickTime&&this.#s(e,t,n)}#d(e){this.dragStarted=!0,this.onDragStart?.(this,e),delete this.onDragStart}isTrackpadGesture(e){const t=performance.now(),n=Math.max(0,t-this.lastWheelEventTime);return this.lastWheelEventTime=t,this.#a(e,t)?this.detectedDevice="mouse":this.#c(n)?this.#p(e)&&this.#m(e,t):(this.#r(e,t),this.hasReceivedWheelEvent=!0),this.detectedDevice==="trackpad"}#a(e,t){return!this.bufferedLinuxEvent||this.bufferedLinuxEventTime<=0?!1:t-this.bufferedLinuxEventTime>Se.maxHighResBufferTime?(this.#l(),!1):e.deltaX===0&&this.#_(this.bufferedLinuxEvent.deltaY,e.deltaY)?(this.#l(),!0):!1}#c(e){const t=!this.hasReceivedWheelEvent,n=e>=Se.trackpadMaxGap;return!t&&!n}#r(e,t){this.#u(e)?this.detectedDevice="trackpad":this.#f(e)?this.detectedDevice="mouse":this.detectedDevice==="trackpad"&&this.#p(e)&&this.#m(e,t)}#l(){this.bufferedLinuxEvent=void 0,this.bufferedLinuxEventTime=0,this.linuxBufferTimeoutId!==void 0&&(clearTimeout(this.linuxBufferTimeoutId),this.linuxBufferTimeoutId=void 0)}#u(e){return!!(e.deltaX!==0&&e.deltaY!==0||e.ctrlKey&&Math.abs(e.deltaY)<10)}#f(e){const t=Math.abs(e.deltaY);return t>80?!0:t>=60&&e.deltaX===0&&this.detectedDevice==="mouse"}#p(e){const t=Math.abs(e.deltaY),n=t>=10&&t<60,i=e.deltaX===0,s=Number.isInteger(e.deltaY);return this.detectedDevice==="trackpad"&&n&&i&&s}#m(e,t){this.linuxBufferTimeoutId!==void 0&&clearTimeout(this.linuxBufferTimeoutId),this.bufferedLinuxEvent=e,this.bufferedLinuxEventTime=t,this.linuxBufferTimeoutId=setTimeout(()=>{this.#l()},Se.maxHighResBufferTime)}#_(e,t){const n=Math.abs(e),i=Math.abs(t);return n===0||i===0?!1:n===i?!0:n%i===0||i%n===0}reset(){this.finally=void 0,delete this.onClick,delete this.onDoubleClick,delete this.onDragStart,delete this.onDrag,delete this.onDragEnd,this.isDown=!1,this.isDouble=!1,this.dragStarted=!1,this.resizeDirection=void 0,this.clearEventsOnReset&&(this.eDown=void 0,this.eMove=void 0,this.eUp=void 0);const{element:e,pointerId:t}=this;this.pointerId=void 0,typeof t=="number"&&e.hasPointerCapture(t)&&e.releasePointerCapture(t)}},N=class extends Error{static{h(this,"NullGraphError")}constructor(o="Attempted to access LGraph reference that was null or undefined.",e){super(o,{cause:e}),this.name="NullGraphError"}};function ko(o){return typeof o=="object"&&o!==null}h(ko,"isRecord");var wo=["title","flags.collapsed","flags.pinned","mode","color","bgcolor"],hs=class{static{h(this,"LGraphNodeProperties")}node;#e=new Set;constructor(o){this.node=o,this.#t()}#t(){for(const o of wo)this.#n(o)}#o(o){let e=this.node;if(o.length===1)return{targetObject:e,propertyName:o[0]};for(let t=0;t<o.length-1;t++){const n=o[t],i=e[n];ko(i)&&(e=i)}return{targetObject:e,propertyName:o[o.length-1]}}#n(o){const e=o.split(".");e.length>1&&this.#c(o);const{targetObject:t,propertyName:n}=this.#o(e),i=Object.prototype.hasOwnProperty.call(t,n),s=t[n];if(i)Object.defineProperty(t,n,this.#s(o,s));else{let a;Object.defineProperty(t,n,{get:h(()=>a,"get"),set:h(r=>{const l=a;a=r,this.#d(o,l,r);const d=r!==void 0,u=Object.getOwnPropertyDescriptor(t,n);u&&u.enumerable!==d&&Object.defineProperty(t,n,{...u,enumerable:d})},"set"),enumerable:!1,configurable:!0})}this.#e.add(o)}#s(o,e){return this.#i(o,e)}#i(o,e){let t=e;return{get:h(()=>t,"get"),set:h(n=>{const i=t;t=n,this.#d(o,i,n)},"set"),enumerable:!0,configurable:!0}}#d(o,e,t){this.#a(o,e,t)}#a(o,e,t){this.node.graph?.trigger("node:property:changed",{nodeId:this.node.id,property:o,oldValue:e,newValue:t})}#c(o){const e=o.split(".");let t=this.node;for(let n=0;n<e.length-1;n++){const i=e[n];t[i]||(t[i]={});const s=t[i];ko(s)&&(t=s)}}isTracked(o){return this.#e.has(o)}getTrackedProperties(){return[...wo]}toJSON(){}};function U(o,...e){return e[0]instanceof o?e[0]:new o(...e)}h(U,"toClass");function XS(o){return typeof o=="object"&&o!==null&&"setColorOption"in o&&"getColorOption"in o}h(XS,"isColorable");function gs(...o){if(!_s(o))return;const e=si(o,"*");if(e.length===0)return"*";const t=fs(...e.map(n=>n.split(",")));if(t.length!==0)return t.join(",")}h(gs,"commonType");function fs(...o){const e={};for(const t of o)for(const n of new Set(t))e[n]=(e[n]??0)+1;return Object.entries(e).filter(([,t])=>t===o.length).map(([t])=>t)}h(fs,"intersection");function _s(o){return o.every(e=>typeof e=="string")}h(_s,"isStrings");var ys=class{static{h(this,"LGraphIcon")}unicode;fontFamily;image;color;bgColor;fontSize;size;circlePadding;xOffset;yOffset;constructor({unicode:o,fontFamily:e="PrimeIcons",image:t,color:n="#e6c200",bgColor:i,fontSize:s=16,size:a,circlePadding:r=2,xOffset:l=0,yOffset:d=0}){this.unicode=o,this.fontFamily=e,this.image=t,this.color=n,this.bgColor=i,this.fontSize=s,this.size=a??s,this.circlePadding=r,this.xOffset=l,this.yOffset=d}draw(o,e,t){if(e+=this.xOffset,t+=this.yOffset,this.image){const n=this.size,i=n/2+this.circlePadding;if(this.bgColor){const{fillStyle:r}=o;o.beginPath(),o.arc(e+i,t,i,0,2*Math.PI),o.fillStyle=this.bgColor,o.fill(),o.fillStyle=r}const s=e+this.circlePadding,a=t-n/2;o.drawImage(this.image,s,a,n,n)}else if(this.unicode){const{font:n,textBaseline:i,textAlign:s,fillStyle:a}=o;o.font=`${this.fontSize}px '${this.fontFamily}'`,o.textBaseline="middle",o.textAlign="center";const r=this.fontSize/2+this.circlePadding;this.bgColor&&(o.beginPath(),o.arc(e+r,t,r,0,2*Math.PI),o.fillStyle=this.bgColor,o.fill()),o.fillStyle=this.color,o.fillText(this.unicode,e+r,t),o.font=n,o.textBaseline=i,o.textAlign=s,o.fillStyle=a}}};let So=(function(o){return o.TopLeft="top-left",o.TopRight="top-right",o})({});var io=class{static{h(this,"LGraphBadge")}text;fgColor;bgColor;fontSize;padding;height;cornerRadius;icon;xOffset;yOffset;constructor({text:o,fgColor:e="white",bgColor:t="#0F1F0F",fontSize:n=12,padding:i=6,height:s=20,cornerRadius:a=5,iconOptions:r,xOffset:l=0,yOffset:d=0}){this.text=o,this.fgColor=e,this.bgColor=t,this.fontSize=n,this.padding=i,this.height=s,this.cornerRadius=a,r&&(this.icon=new ys(r)),this.xOffset=l,this.yOffset=d}get visible(){return(this.text?.length??0)>0||!!this.icon}getWidth(o){if(!this.visible)return 0;const{font:e}=o;let t=0;this.icon&&(this.icon.image?t=this.icon.size+this.padding:this.icon.unicode&&(o.font=`${this.icon.fontSize}px '${this.icon.fontFamily}'`,t=o.measureText(this.icon.unicode).width+this.padding)),o.font=`${this.fontSize}px sans-serif`;const n=this.text?o.measureText(this.text).width:0;return o.font=e,t+n+this.padding*2}draw(o,e,t){if(!this.visible)return;e+=this.xOffset,t+=this.yOffset;const{font:n,fillStyle:i,textBaseline:s,textAlign:a}=o;o.font=`${this.fontSize}px sans-serif`;const r=this.getWidth(o),l=0;o.fillStyle=this.bgColor,o.beginPath(),o.roundRect?o.roundRect(e+l,t,r,this.height,this.cornerRadius):o.rect(e+l,t,r,this.height),o.fill();let d=e+l+this.padding;const u=t+this.height/2;if(this.icon){this.icon.draw(o,d,u);const p=this.icon.image?this.icon.size:this.icon.fontSize;d+=p+this.padding/2+4}this.text&&(o.fillStyle=this.fgColor,o.textBaseline="middle",o.textAlign="left",o.fillText(this.text,d,u+1)),o.font=n,o.fillStyle=i,o.textBaseline=s,o.textAlign=a}},X=class Fe extends Float64Array{static{h(this,"Rectangle")}#e;#t;constructor(e=0,t=0,n=0,i=0){super(4),this[0]=e,this[1]=t,this[2]=n,this[3]=i}static from([e,t,n,i]){return new Fe(e,t,n,i)}static fromCentre([e,t],n,i=n){return new Fe(e-n*.5,t-i*.5,n,i)}static ensureRect(e){return e instanceof Fe?e:new Fe(e[0],e[1],e[2],e[3])}subarray(e=0,t){const n=e<<3,i=t===void 0?t:t-e;return new Float64Array(this.buffer,n,i)}get pos(){return this.#e??=this.subarray(0,2),this.#e}set pos(e){this[0]=e[0],this[1]=e[1]}get size(){return this.#t??=this.subarray(2,4),this.#t}set size(e){this[2]=e[0],this[3]=e[1]}get x(){return this[0]}set x(e){this[0]=e}get y(){return this[1]}set y(e){this[1]=e}get width(){return this[2]}set width(e){this[2]=e}get height(){return this[3]}set height(e){this[3]=e}get left(){return this[0]}set left(e){this[0]=e}get top(){return this[1]}set top(e){this[1]=e}get right(){return this[0]+this[2]}set right(e){this[0]=e-this[2]}get bottom(){return this[1]+this[3]}set bottom(e){this[1]=e-this[3]}get centreX(){return this[0]+this[2]*.5}get centreY(){return this[1]+this[3]*.5}updateTo(e){this[0]=e[0],this[1]=e[1],this[2]=e[2],this[3]=e[3]}containsXy(e,t){const[n,i,s,a]=this;return e>=n&&e<n+s&&t>=i&&t<i+a}containsPoint([e,t]){const[n,i,s,a]=this;return e>=n&&e<n+s&&t>=i&&t<i+a}containsRect(e){const{right:t,bottom:n}=this,i=e[0]+e[2],s=e[1]+e[3];return!(this.x===e[0]&&this.y===e[1]&&t===i&&n===s)&&this.x<=e[0]&&this.y<=e[1]&&t>=i&&n>=s}overlaps(e){return this.x<e[0]+e[2]&&this.y<e[1]+e[3]&&this.x+this.width>e[0]&&this.y+this.height>e[1]}findContainingCorner(e,t,n){if(this.isInTopLeftCorner(e,t,n))return"NW";if(this.isInTopRightCorner(e,t,n))return"NE";if(this.isInBottomLeftCorner(e,t,n))return"SW";if(this.isInBottomRightCorner(e,t,n))return"SE"}isInTopLeftCorner(e,t,n){return G(e,t,this.x,this.y,n,n)}isInTopRightCorner(e,t,n){return G(e,t,this.right-n,this.y,n,n)}isInBottomLeftCorner(e,t,n){return G(e,t,this.x,this.bottom-n,n,n)}isInBottomRightCorner(e,t,n){return G(e,t,this.right-n,this.bottom-n,n,n)}isInTopEdge(e,t,n){return G(e,t,this.x,this.y,this.width,n)}isInBottomEdge(e,t,n){return G(e,t,this.x,this.bottom-n,this.width,n)}isInLeftEdge(e,t,n){return G(e,t,this.x,this.y,n,this.height)}isInRightEdge(e,t,n){return G(e,t,this.right-n,this.y,n,this.height)}getCentre(){return[this.centreX,this.centreY]}getArea(){return this.width*this.height}getPerimeter(){return 2*(this.width+this.height)}getTopLeft(){return[this[0],this[1]]}getBottomRight(){return[this.right,this.bottom]}getSize(){return[this[2],this[3]]}getOffsetTo([e,t]){return[e-this[0],t-this[1]]}getOffsetFrom([e,t]){return[this[0]-e,this[1]-t]}resizeTopLeft(e,t){this[2]+=this[0]-e,this[3]+=this[1]-t,this[0]=e,this[1]=t}resizeBottomLeft(e,t){this[2]+=this[0]-e,this[3]=t-this[1],this[0]=e}resizeTopRight(e,t){this[2]=e-this[0],this[3]+=this[1]-t,this[1]=t}resizeBottomRight(e,t){this[2]=e-this[0],this[3]=t-this[1]}setWidthRightAnchored(e){const t=this[2];this[2]=e,this[0]+=t-e}setHeightBottomAnchored(e){const t=this[3];this[3]=e,this[1]+=t-e}clone(){return new Fe(this[0],this[1],this[2],this[3])}toArray(){return this.export()}export(){return[this[0],this[1],this[2],this[3]]}_drawDebug(e,t="red"){const{strokeStyle:n,lineWidth:i}=e;try{e.strokeStyle=t,e.lineWidth=.5,e.beginPath(),e.strokeRect(this[0],this[1],this[2],this[3])}finally{e.strokeStyle=n,e.lineWidth=i}}},bs=class extends io{static{h(this,"LGraphButton")}name;_last_area=new X;constructor(o){super(o),this.name=o.name}getWidth(o){if(!this.visible)return 0;const{font:e}=o;o.font=`${this.fontSize}px 'PrimeIcons'`;const t=this.text?o.measureText(this.text).width:0;return o.font=e,t}draw(o,e,t){if(!this.visible)return;const n=this.getWidth(o);this._last_area[0]=e+this.xOffset,this._last_area[1]=t+this.yOffset,this._last_area[2]=n,this._last_area[3]=this.height;const i=e+this.xOffset,s=t+this.yOffset,{font:a,fillStyle:r,textBaseline:l,textAlign:d}=o,u=o.fillStyle||"white";o.font=`${this.fontSize}px 'PrimeIcons'`,o.fillStyle=u,o.textBaseline="middle",o.textAlign="center";const p=i+n/2,m=s+this.height/2;this.text&&o.fillText(this.text,p,m),o.font=a,o.fillStyle=r,o.textBaseline=l,o.textAlign=d}isPointInside(o,e){return this._last_area.containsPoint([o,e])}},rt=Ae(),z=class Ee{static{h(this,"LLink")}static _drawDebug=!1;id;parentId;type;origin_id;origin_slot;target_id;target_slot;data;_data;_pos;_last_time;path;_centreAngle;_dragging;#e;get color(){return this.#e}set color(e){this.#e=e===""?null:e}get isFloatingOutput(){return this.origin_id===-1&&this.origin_slot===-1}get isFloatingInput(){return this.target_id===-1&&this.target_slot===-1}get isFloating(){return this.isFloatingOutput||this.isFloatingInput}get originIsIoNode(){return this.origin_id===-10}get targetIsIoNode(){return this.target_id===-20}constructor(e,t,n,i,s,a,r){this.id=e,this.type=t,this.origin_id=n,this.origin_slot=i,this.target_id=s,this.target_slot=a,this.parentId=r,this._data=null,this._pos=[0,0]}static createFromArray(e){return new Ee(e[0],e[5],e[1],e[2],e[3],e[4])}static create(e){return new Ee(e.id,e.type,e.origin_id,e.origin_slot,e.target_id,e.target_slot,e.parentId)}static getReroutes(e,t){return t.parentId===void 0?[]:e.reroutes.get(t.parentId)?.getReroutes()??[]}static getFirstReroute(e,t){return Ee.getReroutes(e,t).at(0)}static findNextReroute(e,t,n){if(t.parentId!==void 0)return e.reroutes.get(t.parentId)?.findNextReroute(n)}static getOriginNode(e,t){const n=e.links.get(t)?.origin_id;return e.getNodeById(n)??void 0}static getTargetNode(e,t){const n=e.links.get(t)?.target_id;return e.getNodeById(n)??void 0}static resolve(e,t){return t.getLink(e)?.resolve(t)}static resolveMany(e,t){const n=[];for(const i of e){const s=t.getLink(i)?.resolve(t);s&&n.push(s)}return n}resolve(e){const t=this.target_id===-1?void 0:e.getNodeById(this.target_id)??void 0,n=t?.inputs[this.target_slot],i=this.originIsIoNode?e.inputNode?.slots[this.origin_slot]:void 0;if(i)return{inputNode:t,input:n,subgraphInput:i,link:this};const s=this.origin_id===-1?void 0:e.getNodeById(this.origin_id)??void 0,a=s?.outputs[this.origin_slot],r=this.targetIsIoNode?e.outputNode?.slots[this.target_slot]:void 0;return r?{outputNode:s,output:a,subgraphInput:void 0,subgraphOutput:r,link:this}:{inputNode:t,outputNode:s,input:n,output:a,subgraphInput:i,subgraphOutput:r,link:this}}configure(e){Array.isArray(e)?(this.id=e[0],this.origin_id=e[1],this.origin_slot=e[2],this.target_id=e[3],this.target_slot=e[4],this.type=e[5]):(this.id=e.id,this.type=e.type,this.origin_id=e.origin_id,this.origin_slot=e.origin_slot,this.target_id=e.target_id,this.target_slot=e.target_slot,this.parentId=e.parentId)}hasOrigin(e,t){return this.origin_id===e&&this.origin_slot===t}hasTarget(e,t){return this.target_id===e&&this.target_slot===t}toFloating(e,t){const n=this.asSerialisable();return n.id=-1,n.parentId=t,e==="input"?(n.origin_id=-1,n.origin_slot=-1):(n.target_id=-1,n.target_slot=-1),Ee.create(n)}disconnect(e,t){const n=Ee.getReroutes(e,this),i=n.at(-1);if(t==="output"&&i?.linkIds.size===1&&i.floatingLinkIds.size===0||t==="input"&&i){const s=Ee.create(this);s.id=-1,t==="input"?(s.origin_id=-1,s.origin_slot=-1,i.floating={slotType:"input"}):(s.target_id=-1,s.target_slot=-1,i.floating={slotType:"output"}),e.addFloatingLink(s)}for(const s of n)s.linkIds.delete(this.id),!t&&!s.totalLinks&&(e.reroutes.delete(s.id),rt.setSource(ue.Canvas),rt.deleteReroute(s.id));e.links.delete(this.id),rt.setSource(ue.Canvas),rt.deleteLink(this.id)}serialize(){return[this.id,this.origin_id,this.origin_slot,this.target_id,this.target_slot,this.type]}asSerialisable(){const e={id:this.id,origin_id:this.origin_id,origin_slot:this.origin_slot,target_id:this.target_id,target_slot:this.target_slot,type:this.type};return this.parentId!==void 0&&(e.parentId=this.parentId),e}};function mn(o,e,t){const{inputs:n}=o;if(n)for(const[i,s]of n.entries()){const a=o.getInputPos(i),r=20+((s.label?.length??s.localized_name?.length??s.name?.length)||3)*7;if(G(e,t,a[0]-10,a[1]-10,r,20))return{index:i,input:s,pos:a}}}h(mn,"getNodeInputOnPos");function hn(o,e,t){const{outputs:n}=o;if(n)for(const[i,s]of n.entries()){const a=o.getOutputPos(i);if(G(e,t,a[0]-10,a[1]-10,40,20))return{index:i,output:s,pos:a}}}h(hn,"getNodeOutputOnPos");function vs(o,e,t,n){const i=mn(o,e,t);return i?(n&&(n[0]=i.pos[0],n[1]=i.pos[1]),i.index):-1}h(vs,"isOverNodeInput");function ks(o,e,t,n){const i=hn(o,e,t);return i?(n&&(n[0]=i.pos[0],n[1]=i.pos[1]),i.index):-1}h(ks,"isOverNodeOutput");var Rt="…",Io="‥",Co="․";let pt=(function(o){return o.Array="array",o[o.Event=-1]="Event",o})({}),Ne=(function(o){return o[o.Box=M.BOX]="Box",o[o.Arrow=M.ARROW]="Arrow",o[o.Grid=M.GRID]="Grid",o[o.Circle=M.CIRCLE]="Circle",o[o.HollowCircle=M.HollowCircle]="HollowCircle",o})({}),ws=(function(o){return o})({}),tt=(function(o){return o.Left="left",o.Right="right",o})({});function gn(o,e,{shape:t=M.BOX,round_radius:n,title_height:i,title_mode:s=se.NORMAL_TITLE,color:a,padding:r=6,collapsed:l=!1,lineWidth:d=1}={}){if(n??=_.ROUND_RADIUS,a??=_.NODE_BOX_OUTLINE_COLOR,s===se.TRANSPARENT_TITLE){const b=i??_.NODE_TITLE_HEIGHT;e[1]-=b,e[3]+=b}const{lineWidth:u,strokeStyle:p}=o;o.lineWidth=d,o.globalAlpha=.8,o.strokeStyle=a,o.beginPath();const[m,g,f,y]=e;switch(t){case M.BOX:o.rect(m-r,g-r,f+2*r,y+2*r);break;case M.ROUND:case M.CARD:{const b=n+r,v=t===M.CARD&&l||t===M.ROUND?[b]:[b,2,b,2];o.roundRect(m-r,g-r,f+2*r,y+2*r,v);break}case M.CIRCLE:{const b=m+f/2,v=g+y/2,k=Math.max(f,y)/2+r;o.arc(b,v,k,0,Math.PI*2);break}}o.stroke(),o.lineWidth=u,o.strokeStyle=p,o.globalAlpha=1}h(gn,"strokeShape");function Ss(o,e,t){if(!(t>0))return"";if(o.measureText(e).width<=t)return e;const n=o.measureText(Rt).width*.75;if(n>t)return o.measureText(Io).width*.75<t?Io:o.measureText(Co).width*.75<t?Co:"";let i=0,s=e.length,a=0;for(;i<=s;){const r=Math.floor((i+s)*.5);if(r===0){i=r+1;continue}const l=e.substring(0,r);o.measureText(l).width+n<=t?(a=r,i=r+1):s=r-1}return a===0?Rt:e.substring(0,a)+Rt}h(Ss,"truncateTextToWidth");function qe({ctx:o,text:e,area:t,align:n="left"}){const{left:i,right:s,bottom:a,width:r,centreX:l}=t;if(o.measureText(e).width<=r){o.textAlign=n;const p=n==="left"?i:n==="right"?s:l;o.fillText(e,p,a);return}const d=Ss(o,e,r);if(d.length===0)return;o.textAlign="left",o.fillText(d.slice(0,-1),i,a),o.rect(i,a,r,1),o.textAlign="right";const u=d.at(-1);o.fillText(u,s,a,o.measureText(u).width*.75)}h(qe,"drawTextInArea");var fn=class{static{h(this,"SlotBase")}name;localized_name;label;type;dir;removable;shape;color_off;color_on;locked;nameLocked;widget;_floatingLinks;hasErrors;boundingRect;constructor(o,e,t){this.name=o,this.type=e,this.boundingRect=t??new X}renderingColor(o){return this.isConnected?this.color_on||o.getConnectedColor(this.type):this.color_off||o.getDisconnectedColor(this.type)}},lt=-Math.PI/2,_n=class extends fn{static{h(this,"NodeSlot")}pos;get#e(){const o=this.node.pos,{boundingRect:e}=this,t=e[3];return Wi([e[0]-o[0],e[1]-o[1],t,t])}#t;get node(){return this.#t}get highlightColor(){return _.NODE_TEXT_HIGHLIGHT_COLOR??_.NODE_SELECTED_TITLE_COLOR??_.NODE_TEXT_COLOR}constructor(o,e){const{boundingRect:t,name:n,type:i,_listenerController:s,...a}=o,r=t?X.ensureRect(t):new X;super(n,i,r),Object.assign(this,a),this.#t=e}get renderingLabel(){return this.label||this.localized_name||this.name||""}draw(o,{colorContext:e,labelPosition:t=tt.Right,lowQuality:n=!1,highlight:i=!1,doStroke:s=!1}){const a=o.fillStyle,r=o.strokeStyle,l=o.lineWidth,d=i?this.highlightColor:_.NODE_TEXT_COLOR,u=this.#e,p=this.type,m=p===pt.Array?Ne.Grid:this.shape;o.save(),o.beginPath();let g=!0;if(o.fillStyle=this.renderingColor(e),o.lineWidth=1,p===pt.Event||m===Ne.Box)o.rect(u[0]-6+.5,u[1]-5+.5,14,10);else if(m===Ne.Arrow)o.moveTo(u[0]+8,u[1]+.5),o.lineTo(u[0]-4,u[1]+6+.5),o.lineTo(u[0]-4,u[1]-6+.5),o.closePath();else if(m===Ne.Grid){for(let v=0;v<3;v++)for(let k=0;k<3;k++)o.rect(u[0]-4+v*3,u[1]-4+k*3,2,2);s=!1}else if(n)o.rect(u[0]-4,u[1]-4,8,8);else{if(m===Ne.HollowCircle){const b=new Path2D;b.arc(u[0],u[1],10,0,Math.PI*2),b.arc(u[0],u[1],i?2.5:1.5,0,Math.PI*2),o.clip(b,"evenodd")}const f=i?5:4,y=[...new Set(`${this.type}`.split(",").map(this.isConnected?b=>e.getConnectedColor(b):b=>e.getDisconnectedColor(b)))].slice(0,3);if(y.length>1){g=!1;const b=Math.PI*2/y.length;y.forEach((v,k)=>{o.moveTo(u[0],u[1]),o.fillStyle=v,o.arc(u[0],u[1],f,b*k+lt,Math.PI*2+lt),o.fill(),o.beginPath()}),o.save(),o.strokeStyle="black",o.lineWidth=.5,y.forEach((v,k)=>{o.moveTo(u[0],u[1]);const w=Math.cos(b*k+lt)*f,S=Math.sin(b*k+lt)*f;o.lineTo(u[0]+w,u[1]+S)}),o.stroke(),o.restore(),o.beginPath()}o.arc(u[0],u[1],f,0,Math.PI*2)}if(g&&o.fill(),!n&&s&&o.stroke(),o.restore(),!(n||this.isWidgetInputSlot)){const f=this.renderingLabel;f&&(o.fillStyle=d,t===tt.Right?this.dir==O.UP?o.fillText(f,u[0],u[1]-10):o.fillText(f,u[0]+10,u[1]+5):this.dir==O.DOWN?o.fillText(f,u[0],u[1]-8):o.fillText(f,u[0]-10,u[1]+5))}this.hasErrors&&(o.lineWidth=2,o.strokeStyle="red",o.beginPath(),o.arc(u[0],u[1],12,0,Math.PI*2),o.stroke()),o.fillStyle=a,o.strokeStyle=r,o.lineWidth=l}drawCollapsed(o){const[e,t]=this.collapsedPos,{fillStyle:n}=o;o.fillStyle="#686",o.beginPath(),this.type===pt.Event||this.shape===M.BOX?o.rect(e-7+.5,t-4,14,8):this.shape===M.ARROW?(this instanceof Be?(o.moveTo(e+8,t),o.lineTo(e-4,t-4),o.lineTo(e-4,t+4)):(o.moveTo(e+6,t),o.lineTo(e-6,t-4),o.lineTo(e-6,t+4)),o.closePath()):o.arc(e,t,4,0,Math.PI*2),o.fill(),o.fillStyle=n}},To=Ae(),J=class Z{static{h(this,"Reroute")}static radius=10;static maxSplineOffset=80;static drawIdBadge=!1;static slotRadius=5;static get slotOffset(){const e=Z.slotRadius*.33;return Z.radius+e+Z.slotRadius}network;parentIdInternal;get parentId(){return this.parentIdInternal}set parentId(e){e!==this.id&&this.getReroutes()!==null&&(this.parentIdInternal=e)}get parent(){return this.network.deref()?.getReroute(this.parentIdInternal)}floating;posInternal=[0,0];get pos(){return this.posInternal}set pos(e){if(!(e?.length>=2))throw new TypeError("Reroute.pos is an x,y point, and expects an indexable with at least two values.");this.posInternal[0]=e[0],this.posInternal[1]=e[1]}get boundingRect(){const{radius:e}=Z,[t,n]=this.posInternal;return[t-e,n-e,2*e,2*e]}get hoverArea(){const e=2*Z.slotOffset,t=2*Math.max(Z.radius,Z.slotRadius),[n,i]=this.posInternal;return[n-e,i-t,2*e,2*t]}get totalLinks(){return this.linkIds.size+this.floatingLinkIds.size}selected;linkIds;floatingLinkIds;cos=0;sin=0;controlPoint=[0,0];path;_centreAngle;_pos=[0,0];_dragging;_colour;get colour(){return this._colour??"#18184d"}lastRenderTime=-1/0;inputSlot=new Lo(this,!0);outputSlot=new Lo(this,!1);get isSlotHovered(){return this.isInputHovered||this.isOutputHovered}get isInputHovered(){return this.inputSlot.hovering}get isOutputHovered(){return this.outputSlot.hovering}get firstLink(){const e=this.linkIds.values().next().value;return e===void 0?void 0:this.network.deref()?.links.get(e)}get firstFloatingLink(){const e=this.floatingLinkIds.values().next().value;return e===void 0?void 0:this.network.deref()?.floatingLinks.get(e)}get origin_id(){return this.firstLink?.origin_id}get origin_slot(){return this.firstLink?.origin_slot}constructor(e,t,n,i,s,a){this.id=e,this.network=new WeakRef(t),this.parentId=i,n&&(this.pos=n),this.linkIds=new Set(s),this.floatingLinkIds=new Set(a)}update(e,t,n,i){this.parentId=e,t&&(this.pos=t),n&&(this.linkIds=new Set(n)),this.floating=i}validateLinks(e,t){const{linkIds:n,floatingLinkIds:i}=this;for(const s of n)e.has(s)||n.delete(s);for(const s of i)t.has(s)||i.delete(s);return n.size>0||i.size>0}getReroutes(e=new Set){if(this.parentIdInternal===void 0)return[this];if(e.has(this))return null;e.add(this);const t=this.network.deref()?.reroutes.get(this.parentIdInternal);if(!t)return this.parentIdInternal=void 0,[this];const n=t.getReroutes(e);return n?.push(this),n}findNextReroute(e,t=new Set){if(this.parentIdInternal===e)return this;if(t.has(this))return null;if(t.add(this),this.parentIdInternal!==void 0)return this.network.deref()?.reroutes.get(this.parentIdInternal)?.findNextReroute(e,t)}findSourceOutput(){const e=this.firstLink??this.firstFloatingLink;if(!e)return;const t=this.network.deref()?.getNodeById(e.origin_id);if(t)return{node:t,output:t.outputs[e.origin_slot]}}findTargetInputs(){const e=this.network.deref();if(!e)return;const t=[];return n(e,this.linkIds,e.links),n(e,this.floatingLinkIds,e.floatingLinks),t;function n(i,s,a){for(const r of s){const l=a.get(r);if(!l)continue;const d=i.getNodeById(l.target_id),u=d?.inputs[l.target_slot];u&&t.push({node:d,input:u,link:l})}}h(n,"addAllResults")}getFloatingLinks(e){const t=this.network.deref()?.floatingLinks;if(!t)return;const n=e==="input"?"origin_id":"target_id",i=[];for(const s of this.floatingLinkIds){const a=t.get(s);a?.[n]===-1&&i.push(a)}return i}setFloatingLinkOrigin(e,t,n){const i=this.network.deref(),s=this.getFloatingLinks("output");if(!s)throw new Error("[setFloatingLinkOrigin]: Invalid network.");if(s.length){t._floatingLinks??=new Set;for(const a of s)t._floatingLinks.add(a),i?.getNodeById(a.origin_id)?.outputs[a.origin_slot]?._floatingLinks?.delete(a),a.origin_id=e.id,a.origin_slot=n}}move(e,t){const n={x:this.posInternal[0],y:this.posInternal[1]};this.posInternal[0]+=e,this.posInternal[1]+=t,To.setSource(ue.Canvas),To.moveReroute(this.id,{x:this.posInternal[0],y:this.posInternal[1]},n)}snapToGrid(e){if(!e)return!1;const{pos:t}=this;return t[0]=e*Math.round(t[0]/e),t[1]=e*Math.round(t[1]/e),!0}removeAllFloatingLinks(){for(const e of this.floatingLinkIds)this.removeFloatingLink(e)}removeFloatingLink(e){const t=this.network.deref();if(!t)return;const n=t.floatingLinks.get(e);if(!n){console.warn(`[Reroute.removeFloatingLink] Floating link not found: ${e}, ignoring and discarding ID.`),this.floatingLinkIds.delete(e);return}t.removeFloatingLink(n)}removeLink(e){const t=this.network.deref();t&&(e===t.floatingLinks.get(e.id)?this.floatingLinkIds.delete(e.id):this.linkIds.delete(e.id))}remove(){const e=this.network.deref();e&&e.removeReroute(this.id)}calculateAngle(e,t,n){if(!(e>this.lastRenderTime))return;this.lastRenderTime=e;const{id:i,pos:s}=this,a=[];let r=0;if(f(this.linkIds,t.links),f(this.floatingLinkIds,t.floatingLinks),!a.length){this.cos=0,this.sin=0,this.controlPoint[0]=0,this.controlPoint[1]=0;return}r/=a.length;const l=Math.atan2(this.posInternal[1]-n[1],this.posInternal[0]-n[0]);let d=(l-r)*.5;Math.abs(d)>Math.PI*.5&&(d+=Math.PI);const u=Math.min(Z.maxSplineOffset,Ue(n,this.posInternal)*.25),p=l-d,m=Math.cos(p),g=Math.sin(p);this.cos=m,this.sin=g,this.controlPoint[0]=u*-m,this.controlPoint[1]=u*-g;function f(y,b){for(const v of y){const k=Is(t,b.get(v),i);if(!k)continue;const w=Cs(s,k);a.push(w),r+=w}}h(f,"calculateAngles")}draw(e,t){const{globalAlpha:n}=e,{pos:i}=this;if(e.beginPath(),e.arc(i[0],i[1],Z.radius,0,2*Math.PI),this.linkIds.size===0&&(e.fillStyle=t??"#797979",e.fill(),e.globalAlpha=n*.33),e.fillStyle=this.colour,e.lineWidth=Z.radius*.1,e.strokeStyle="rgb(0,0,0,0.5)",e.fill(),e.stroke(),e.fillStyle="#ffffff55",e.strokeStyle="rgb(0,0,0,0.3)",e.beginPath(),e.arc(i[0],i[1],Z.radius*.8,0,2*Math.PI),e.fill(),e.stroke(),this.selected&&(e.strokeStyle="#fff",e.beginPath(),e.arc(i[0],i[1],Z.radius*1.2,0,2*Math.PI),e.stroke()),Z.drawIdBadge){const s=new io({text:this.id.toString()}),a=i[0]-s.getWidth(e)*.5,r=i[1]-s.height-Z.radius-2;s.draw(e,a,r)}e.globalAlpha=n}drawSlots(e){this.inputSlot.draw(e),this.outputSlot.draw(e)}drawHighlight(e,t){const{pos:n}=this,{strokeStyle:i,lineWidth:s}=e;e.strokeStyle=t,e.lineWidth=1,e.beginPath(),e.arc(n[0],n[1],Z.radius*1.5,0,2*Math.PI),e.stroke(),e.strokeStyle=i,e.lineWidth=s}updateVisibility(e){const t=this.inputSlot,n=this.outputSlot;t.dirty=!1,n.dirty=!1;const{firstFloatingLink:i}=this,s=!!this.firstLink,a=s||i?.isFloatingOutput,r=s||i?.isFloatingInput;if((a||r)&&We(e,this.hoverArea)){const l=this.contains(e);a&&t.update(e,l),r&&n.update(e,l)}else this.hideSlots();return t.dirty||n.dirty}hideSlots(){this.inputSlot.hide(),this.outputSlot.hide()}containsPoint(e){return We(e,this.hoverArea)&&this.contains(e)}contains(e){return Ue(this.pos,e)<=Z.radius}asSerialisable(){const{id:e,parentId:t,pos:n,linkIds:i}=this;return{id:e,parentId:t,pos:[n[0],n[1]],linkIds:[...i],floating:this.floating?{slotType:this.floating.slotType}:void 0}}},Lo=class{static{h(this,"RerouteSlot")}reroute;offsetMultiplier;get pos(){const[o,e]=this.reroute.pos;return[o+J.slotOffset*this.offsetMultiplier,e]}dirty=!1;hoveringInternal=!1;get hovering(){return this.hoveringInternal}set hovering(o){Object.is(this.hoveringInternal,o)||(this.hoveringInternal=o,this.dirty=!0)}showOutlineInternal=!1;get showOutline(){return this.showOutlineInternal}set showOutline(o){Object.is(this.showOutlineInternal,o)||(this.showOutlineInternal=o,this.dirty=!0)}constructor(o,e){this.reroute=o,this.offsetMultiplier=e?-1:1}update(o,e){if(e)this.hovering=!1,this.showOutline=!0;else{const t=Ue(this.pos,o);this.hovering=t<=2*J.slotRadius,this.showOutline=t<=5*J.slotRadius}}hide(){this.hovering=!1,this.showOutline=!1}draw(o){const{fillStyle:e,strokeStyle:t,lineWidth:n}=o,{showOutline:i,hovering:s,pos:[a,r]}=this;if(i)try{o.fillStyle=s?this.reroute.colour:"rgba(127,127,127,0.3)",o.strokeStyle="rgb(0,0,0,0.5)",o.lineWidth=1,o.beginPath(),o.arc(a,r,J.slotRadius,0,2*Math.PI),o.fill(),o.stroke()}finally{o.fillStyle=e,o.strokeStyle=t,o.lineWidth=n}}};function Is(o,e,t){if(!e)return;const n=z.findNextReroute(o,e,t)?.pos;if(n)return n;if(!(e.target_id===-1||e.target_slot===-1))return o.getNodeById(e.target_id)?.getInputPos(e.target_slot)}h(Is,"getNextPos");function Cs(o,e){return Math.atan2(e[1]-o[1],e[0]-o[0])}h(Cs,"getDirection");function Eo(o){return o==""||o=="0"?["*"]:String(o).toLowerCase().split(",")}h(Eo,"parseSlotTypes");function He(o,e=[]){let t=1;const n=o;for(;e.includes(o);)o=`${n}_${t++}`;return o}h(He,"nextUniqueName");function yn(o){const e=new Set;if(o)for(const n of o)t(n,e);return e;function t(n,i){if(!(i.has(n)||n.pinned)&&(i.add(n),n.children))for(const s of n.children)t(s,i)}}h(yn,"getAllNestedItems");function Ts(o){for(const e of o)if(e instanceof q)return e}h(Ts,"findFirstNode");function vt(o,e,t){if(!o?.length)return;let n,i,s;const a=Eo(e);for(const[r,l]of o.entries()){const d=Eo(l.type);for(const u of a)for(const p of d)if(p===u){if(t(l))return{index:r,slot:l};n??={index:r,slot:l}}else!i&&(u==="*"||p==="*")&&(t(l)?i={index:r,slot:l}:s??={index:r,slot:l})}return i??n??s}h(vt,"findFreeSlotOfType");var Et=class extends EventTarget{static{h(this,"CustomEventTarget")}dispatch(o,e){const t=new CustomEvent(o,{detail:e,cancelable:!0});return super.dispatchEvent(t)}addEventListener(o,e,t){super.addEventListener(o,e,t)}removeEventListener(o,e,t){super.removeEventListener(o,e,t)}dispatchEvent(o){return super.dispatchEvent(o)}},Ls=class Xt{static{h(this,"ConstrainedSize")}#e=0;#t=0;#o=0;#n=0;minWidth=0;minHeight=0;maxWidth=1/0;maxHeight=1/0;get width(){return this.#e}get height(){return this.#t}get desiredWidth(){return this.#o}set desiredWidth(e){this.#o=e,this.#e=pe(e,this.minWidth,this.maxWidth)}get desiredHeight(){return this.#n}set desiredHeight(e){this.#n=e,this.#t=pe(e,this.minHeight,this.maxHeight)}constructor(e,t){this.desiredWidth=e,this.desiredHeight=t}static fromSize(e){return new Xt(e[0],e[1])}static fromRect(e){return new Xt(e[2],e[3])}setSize(e){this.desiredWidth=e[0],this.desiredHeight=e[1]}setValues(e,t){this.desiredWidth=e,this.desiredHeight=t}toSize(){return[this.#e,this.#t]}},so=class Ye extends fn{static{h(this,"SubgraphSlot")}static get defaultHeight(){return _.NODE_SLOT_HEIGHT}#e=[0,0];measurement=new Ls(Ye.defaultHeight,Ye.defaultHeight);id;parent;type;linkIds=[];boundingRect=new X(0,0,0,Ye.defaultHeight);get pos(){return this.#e}set pos(e){!e||e.length<2||(this.#e[0]=e[0],this.#e[1]=e[1])}get isConnected(){return this.linkIds.length>0}get displayName(){return this.label??this.localized_name??this.name}constructor(e,t){super(e.name,e.type),Object.assign(this,e),this.id=e.id??fe(),this.type=e.type,this.parent=t}isPointerOver=!1;containsPoint(e){return this.boundingRect.containsPoint(e)}onPointerMove(e){this.isPointerOver=this.boundingRect.containsXy(e.canvasX,e.canvasY)}getLinks(){const e=[],{subgraph:t}=this.parent;for(const n of this.linkIds){const i=t.getLink(n);i&&e.push(i)}return e}decrementSlots(e){const{links:t}=this.parent.subgraph,n=e==="inputs"?"origin_slot":"target_slot";for(const i of this.linkIds){const s=t.get(i);s?s[n]--:console.warn("decrementSlots: link ID not found",i)}}measure(){const e=ce._measureText?.(this.displayName)??0,{defaultHeight:t}=Ye;return this.measurement.setValues(e+t,t),this.measurement.toSize()}disconnect(){const{subgraph:e}=this.parent;for(const t of this.linkIds)e.removeLink(t);this.linkIds.length=0}draw({ctx:e,colorContext:t,lowQuality:n,fromSlot:i,editorAlpha:s=1}){const a=this.shape,{isPointerOver:r,pos:[l,d]}=this,u=i?this.isValidTarget(i):!0,p=!i||u,m=p&&r,g=e.globalAlpha;e.globalAlpha=p?s:.4*s,e.beginPath();const f=this.renderingColor(t);if(n)e.fillStyle=f,e.rect(l-4,d-4,8,8),e.fill();else if(a===Ne.HollowCircle){e.lineWidth=3,e.strokeStyle=f;const y=m?4:3;e.arc(l,d,y,0,Math.PI*2),e.stroke()}else{e.fillStyle=f;const y=m?5:4;e.arc(l,d,y,0,Math.PI*2),e.fill()}if(this.displayName){const[y,b]=this.labelPos;e.fillStyle=m?"white":_.NODE_TEXT_COLOR||"#AAA",e.fillText(this.displayName,y,b)}e.globalAlpha=g}asSerialisable(){const{id:e,name:t,type:n,linkIds:i,localized_name:s,label:a,dir:r,shape:l,color_off:d,color_on:u,pos:p}=this;return{id:e,name:t,type:n,linkIds:i,localized_name:s,label:a,dir:r,shape:l,color_off:d,color_on:u,pos:p}}},kt=class extends so{static{h(this,"SubgraphInput")}events=new Et;#e;get _widget(){return this.#e?.deref()}set _widget(o){this.#e=o?new WeakRef(o):void 0}connect(o,e,t){const{subgraph:n}=this.parent,i=e.inputs.indexOf(o);if(e.onConnectInput?.(i,this.type,this,this.parent,-1)===!1)return;if(o.link!=null){n.beforeChange();const d=n.getLink(o.link);this.parent._disconnectNodeInput(e,o,d)}const s=e.getWidgetFromSlot(o);if(s){if(!this.matchesWidget(s)){console.warn("Target input has invalid widget.",o,e);return}this._widget??=s,this.events.dispatch("input-connected",{input:o,widget:s})}const a=new z(++n.state.lastLinkId,o.type,this.parent.id,this.parent.slots.indexOf(this),e.id,i,t);n._links.set(a.id,a),this.linkIds.push(a.id),o.link=a.id;const r=z.getReroutes(n,a);for(const d of r)d.linkIds.add(a.id),d.floating&&delete d.floating,d._dragging=void 0;const l=r.at(-1);if(l)for(const d of l.floatingLinkIds){const u=n.floatingLinks.get(d);u?.parentId===l.id&&n.removeFloatingLink(u)}return n._version++,e.onConnectionsChange?.(j.INPUT,i,!0,a,o),n.afterChange(),a}get labelPos(){const[o,e,,t]=this.boundingRect;return[o,e+t*.5]}getConnectedWidgets(){const{subgraph:o}=this.parent,e=[];for(const t of this.linkIds){const n=o.getLink(t);if(!n){console.error("Link not found",t);continue}const i=n.resolve(o);if(i.input&&i.inputNode?.widgets){const s=i.input.widget;if(!s)continue;if(!s.name){console.warn("Invalid widget name",s);continue}const a=i.inputNode.widgets.find(r=>r.name===s.name);if(!a){console.warn("Widget not found",s);continue}e.push(a)}}return e}matchesWidget(o){const e=this.#e?.deref();return e?!(o.type!==e.type||o.options.min!==e.options.min||o.options.max!==e.options.max||o.options.step!==e.options.step||o.options.step2!==e.options.step2||o.options.precision!==e.options.precision):!0}disconnect(){super.disconnect(),this.events.dispatch("input-disconnected",{input:this})}arrange(o){const[e,t,n,i]=o,{boundingRect:s,pos:a}=this;s[0]=e-n,s[1]=t,s[2]=n,s[3]=i,a[0]=e-i*.5,a[1]=t+i*.5}isValidTarget(o){return Cn(o)?"link"in o&&_.isValidConnection(this.type,o.type):In(o)?_.isValidConnection(this.type,o.type):!1}},bn=class extends kt{static{h(this,"EmptySubgraphInput")}constructor(o){super({id:bt,name:"",type:""},o)}connect(o,e,t){const{subgraph:n}=this.parent,i=n.inputs.map(a=>a.name),s=He(o.name,i);return n.addInput(s,String(o.type)).connect(o,e,t)}get labelPos(){const[o,e,,t]=this.boundingRect;return[o,e+t*.5]}},_e=class vn{static{h(this,"SubgraphIONodeBase")}static margin=10;static minWidth=100;static roundedRadius=10;#e=new X;get boundingRect(){return this.#e}selected=!1;pinned=!1;removable=!1;isPointerOver=!1;get pos(){return this.boundingRect.pos}set pos(e){this.boundingRect.pos=e}get size(){return this.boundingRect.size}set size(e){this.boundingRect.size=e}get sideLineWidth(){return this.isPointerOver?2.5:2}get sideStrokeStyle(){return this.isPointerOver?"white":"#efefef"}constructor(e){this.subgraph=e}move(e,t){this.pos[0]+=e,this.pos[1]+=t}snapToGrid(e){return this.pinned?!1:xe(this.pos,e)}containsPoint(e){return this.boundingRect.containsPoint(e)}onPointerMove(e){const t=this.boundingRect.containsXy(e.canvasX,e.canvasY);let n=t?te.SubgraphIoNode:te.Nothing;if(t){this.isPointerOver||this.onPointerEnter();for(const i of this.allSlots)i.onPointerMove(e),i.isPointerOver&&(n|=te.SubgraphIoSlot)}else this.isPointerOver&&this.onPointerLeave();return n}onPointerEnter(){this.isPointerOver=!0}onPointerLeave(){this.isPointerOver=!1;for(const e of this.slots)e.isPointerOver=!1}getSlotInPosition(e,t){for(const n of this.allSlots)if(n.boundingRect.containsXy(e,t))return n}handleSlotDoubleClick(e,t){e!==this.emptySlot&&this.#n(e,t)}showSlotContextMenu(e,t){const n=this.#t(e);n.length>0&&new _.ContextMenu(n,{event:t,title:e.name||"Subgraph Output",callback:h(i=>{this.#o(i,e,t)},"callback")})}#t(e){const t=[];return e!==this.emptySlot&&e.linkIds.length>0&&t.push({content:"Disconnect Links",value:"disconnect"}),e!==this.emptySlot&&t.push({content:"Rename Slot",value:"rename"}),e!==this.emptySlot&&(t.push(null),t.push({content:"Remove Slot",value:"remove",className:"danger"})),t}#o(e,t,n){switch(e.value){case"disconnect":t.disconnect();break;case"remove":t!==this.emptySlot&&this.removeSlot(t);break;case"rename":t!==this.emptySlot&&this.#n(t,n);break}this.subgraph.setDirtyCanvas(!0)}#n(e,t){this.subgraph.canvasAction(n=>n.prompt("Slot name",e.displayName,i=>{i&&this.renameSlot(e,i)},t))}arrange(){const{minWidth:e,roundedRadius:t}=vn,[,n]=this.boundingRect,i=this.slotAnchorX,{size:s}=this;let a=e,r=n+t;for(const l of this.allSlots){const[d,u]=l.measure();l.arrange([i,r,d,u]),r+=u,d>a&&(a=d)}s[0]=a+2*t,s[1]=r-n+t}draw(e,t,n,i){const{lineWidth:s,strokeStyle:a,fillStyle:r,font:l,textBaseline:d}=e;this.drawProtected(e,t,n,i),Object.assign(e,{lineWidth:s,strokeStyle:a,fillStyle:r,font:l,textBaseline:d})}drawSlots(e,t,n,i){e.fillStyle="#AAA",e.font="12px Inter, sans-serif",e.textBaseline="middle";for(const s of this.allSlots)s.draw({ctx:e,colorContext:t,fromSlot:n,editorAlpha:i})}configure(e){this.#e.set(e.bounding),this.pinned=e.pinned??!1}asSerialisable(){return{id:this.id,bounding:this.boundingRect.export(),pinned:this.pinned?!0:void 0}}},Nt=class extends _e{static{h(this,"SubgraphInputNode")}id=-10;emptySlot=new bn(this);get slots(){return this.subgraph.inputs}get allSlots(){return[...this.slots,this.emptySlot]}get slotAnchorX(){const[o,,e]=this.boundingRect;return o+e-_e.roundedRadius}onPointerDown(o,e,t){if(o.button===0)for(const n of this.allSlots)n.boundingRect.containsXy(o.canvasX,o.canvasY)&&(e.onDragStart=()=>{t.dragNewFromSubgraphInput(this.subgraph,this,n)},e.onDragEnd=i=>{t.dropLinks(this.subgraph,i)},e.onDoubleClick=()=>{this.handleSlotDoubleClick(n,o)},e.finally=()=>{t.reset(!0)});else if(o.button===2){const n=this.getSlotInPosition(o.canvasX,o.canvasY);n&&this.showSlotContextMenu(n,o)}}renameSlot(o,e){this.subgraph.renameInput(o,e)}removeSlot(o){this.subgraph.removeInput(o)}canConnectTo(o,e,t){return o.canConnectTo(this,e,t)}connectSlots(o,e,t,n){const{subgraph:i}=this,s=this.slots.indexOf(o),a=e.inputs.indexOf(t);if(s===-1||a===-1)throw new Error("Invalid slot indices.");return new z(++i.state.lastLinkId,t.type||o.type,this.id,s,e.id,a,n)}connectByType(o,e,t,n){const i=e.findInputByType(t);if(i){if(o===-1){const s=this.subgraph.addInput(i.slot.name,String(i.slot.type??"")),a=this.slots.indexOf(s);if(a===-1){console.error("Could not find newly created subgraph input slot.");return}o=a}return this.slots[o].connect(i.slot,e,n?.afterRerouteId)}}findOutputSlot(o){return this.slots.find(e=>e.name===o)}findOutputByType(o){return vt(this.slots,o,e=>e.linkIds.length>0)?.slot}_disconnectNodeInput(o,e,t){const{subgraph:n}=this;if(e._floatingLinks?.size)for(const l of e._floatingLinks)n.removeFloatingLink(l);if(e.link=null,n.setDirtyCanvas(!1,!0),!t)return;const i=t.origin_slot;t.disconnect(n,"output"),n._version++;const s=this.slots.at(i);if(!s){console.warn("disconnectNodeInput: subgraphInput not found",this,i);return}const a=s.linkIds.indexOf(t.id);a!==-1?s.linkIds.splice(a,1):console.warn("disconnectNodeInput: link ID not found in subgraphInput linkIds",t.id);const r=o.inputs.findIndex(l=>l===e);r!==-1&&o.onConnectionsChange?.(j.INPUT,r,!1,t,s)}drawProtected(o,e,t,n){const{roundedRadius:i}=_e,s=o.getTransform(),[a,r,l,d]=this.boundingRect;o.translate(a,r),o.strokeStyle=this.sideStrokeStyle,o.lineWidth=this.sideLineWidth,o.beginPath(),o.arc(l-i,i,i,Math.PI*1.5,0),o.moveTo(l,i),o.lineTo(l,d-i),o.arc(l-i,d-i,i,0,Math.PI*.5),o.stroke(),o.setTransform(s),this.drawSlots(o,e,t,n)}},wt=class extends so{static{h(this,"SubgraphOutput")}connect(o,e,t){const{subgraph:n}=this.parent;if(!_.isValidConnection(o.type,this.type))return;const i=e.outputs.indexOf(o);if(i===-1)throw new Error("Slot is not an output of the given node");if(e.onConnectOutput?.(i,this.type,this,this.parent,-1)===!1)return;const s=this.getLinks().at(0);if(s!=null){n.beforeChange(),s.disconnect(n,"input");const d=s.resolve(n).output?.links;d&&ai(d,s.id)}const a=new z(++n.state.lastLinkId,o.type,e.id,i,this.parent.id,this.parent.slots.indexOf(this),t);n._links.set(a.id,a),this.linkIds[0]=a.id,o.links??=[],o.links.push(a.id);const r=z.getReroutes(n,a);for(const d of r)d.linkIds.add(a.id),d.floating&&delete d.floating,d._dragging=void 0;const l=r.at(-1);if(l)for(const d of l.floatingLinkIds){const u=n.floatingLinks.get(d);u?.parentId===l.id&&n.removeFloatingLink(u)}return n._version++,e.onConnectionsChange?.(j.OUTPUT,i,!0,a,o),n.afterChange(),a}get labelPos(){const[o,e,,t]=this.boundingRect;return[o+t,e+t*.5]}arrange(o){const[e,t,n,i]=o,{boundingRect:s,pos:a}=this;s[0]=e,s[1]=t,s[2]=n,s[3]=i,a[0]=e+i*.5,a[1]=t+i*.5}isValidTarget(o){return Cn(o)?"links"in o&&_.isValidConnection(o.type,this.type):Sn(o)?_.isValidConnection(o.type,this.type):!1}disconnect(){const{subgraph:o}=this.parent;for(const e of this.linkIds){const t=o.links[e];if(!t)continue;o.removeLink(e);const{output:n,outputNode:i}=t.resolve(o);n&&(n.links=n.links?.filter(s=>s!==e)??null),i?.onConnectionsChange?.(j.OUTPUT,t.origin_slot,!1,t,this)}this.linkIds.length=0}},kn=class extends wt{static{h(this,"EmptySubgraphOutput")}constructor(o){super({id:bt,name:"",type:""},o)}connect(o,e,t){const{subgraph:n}=this.parent,i=n.outputs.map(a=>a.name),s=He(o.name,i);return n.addOutput(s,String(o.type)).connect(o,e,t)}get labelPos(){const[o,e,,t]=this.boundingRect;return[o,e+t*.5]}},xt=class extends _e{static{h(this,"SubgraphOutputNode")}id=-20;emptySlot=new kn(this);get slots(){return this.subgraph.outputs}get allSlots(){return[...this.slots,this.emptySlot]}get slotAnchorX(){const[o]=this.boundingRect;return o+_e.roundedRadius}onPointerDown(o,e,t){if(o.button===0)for(const n of this.allSlots)n.boundingRect.containsXy(o.canvasX,o.canvasY)&&(e.onDragStart=()=>{t.dragNewFromSubgraphOutput(this.subgraph,this,n)},e.onDragEnd=i=>{t.dropLinks(this.subgraph,i)},e.onDoubleClick=()=>{this.handleSlotDoubleClick(n,o)},e.finally=()=>{t.reset(!0)});else if(o.button===2){const n=this.getSlotInPosition(o.canvasX,o.canvasY);n&&this.showSlotContextMenu(n,o)}}renameSlot(o,e){this.subgraph.renameOutput(o,e)}removeSlot(o){this.subgraph.removeOutput(o)}canConnectTo(o,e,t){return o.canConnectTo(this,e,t)}connectByTypeOutput(o,e,t,n){const i=e.findOutputByType(t);if(i)return this.slots[o].connect(i.slot,e,n?.afterRerouteId)}findInputByType(o){return vt(this.slots,o,e=>e.linkIds.length>0)?.slot}drawProtected(o,e,t,n){const{roundedRadius:i}=_e,s=o.getTransform(),[a,r,,l]=this.boundingRect;o.translate(a,r),o.strokeStyle=this.sideStrokeStyle,o.lineWidth=this.sideLineWidth,o.beginPath(),o.arc(i,i,i,Math.PI,Math.PI*1.5),o.moveTo(0,i),o.lineTo(0,l-i),o.arc(i,l-i,i,Math.PI,Math.PI*.5,!0),o.stroke(),o.setTransform(s),this.drawSlots(o,e,t,n)}};function Es(o){const e=new Set,t=new Set,n=new Set,i=new Set,s=new Set,a=new Set;for(const r of o)switch(!0){case r instanceof q:e.add(r);break;case r instanceof de:n.add(r);break;case r instanceof J:t.add(r);break;case r instanceof Nt:i.add(r);break;case r instanceof xt:s.add(r);break;default:a.add(r);break}return{nodes:e,reroutes:t,groups:n,subgraphInputNodes:i,subgraphOutputNodes:s,unknown:a}}h(Es,"splitPositionables");function Ns(o,e){const t=[],n=[],i=[],s=[],a=[],r=new WeakSet;for(const d of e)if(!r.has(d)){if(r.add(d),d instanceof q){const u=d;if(u.inputs)for(const p of u.inputs){if(l(p._floatingLinks),p.link==null)continue;const m=z.resolve(p.link,o);if(!m){console.warn(`Failed to resolve link ID [${p.link}]`);continue}const{link:g,outputNode:f}=m;f?e.has(f)?t.push(g):i.push(g):g.origin_id===-10&&i.push(g)}if(u.outputs)for(const p of u.outputs){if(l(p._floatingLinks),!p.links)continue;const m=z.resolveMany(p.links,o);for(const{link:g,inputNode:f}of m)(g.target_id===-20||f&&!e.has(f))&&s.push(g)}}else if(d instanceof J){const u=d,p=z.resolveMany(u.linkIds,o);for(const{link:m}of p){const g=z.getReroutes(o,m).filter(b=>!e.has(b)),{inputNode:f,outputNode:y}=m.resolve(o);(g.length||f&&!e.has(f)||y&&!e.has(y))&&n.push(m)}}}return{boundaryLinks:n,boundaryFloatingLinks:a,internalLinks:t,boundaryInputLinks:i,boundaryOutputLinks:s};function l(d){if(d)for(const u of d)z.getReroutes(o,u).some(p=>!e.has(p))&&a.push(u)}}h(Ns,"getBoundaryLinks");function No(o){const e=[];for(const t of o){const n=_.createNode(t.type);if(!n){console.warn("Failed to create node",t.type);const s=structuredClone(t.serialize());e.push(s);continue}const i=structuredClone(t.serialize());n.configure(i),e.push(n.serialize())}return e}h(No,"multiClone");function St(o){const e=new Map;for(const t of o){const n=t.subgraphInput??t.output??{},i=e.get(n);i?i.push(t):e.set(n,[t])}return e}h(St,"groupResolvedByOutput");function wn(o,e){let t=o,n=t.parentId===void 0?void 0:e.get(t.parentId);for(;t.parentId!==void 0&&n;)t=n,n=t.parentId===void 0?void 0:e.get(t.parentId);const i=t.parentId;return t.parentId=void 0,i}h(wn,"mapReroutes");function xs(o,e,t){const n=St(o),i=[];for(const[,s]of n){const a=[];for(const S of s){const{link:E,input:C}=S;if(!C)continue;const I=E.asSerialisable();E.parentId=wn(E,t),I.origin_id=-10,I.origin_slot=i.length,e.push(I),a.push(I)}const{input:r}=s[0];if(!r)continue;const{color_off:l,color_on:d,dir:u,hasErrors:p,label:m,localized_name:g,name:f,shape:y,type:b}=r,v=He(f,i.map(S=>S.name)),k=g?He(g,i.map(S=>S.localized_name??"")):void 0,w={id:fe(),type:String(b),linkIds:a.map(S=>S.id),name:v,color_off:l,color_on:d,dir:u,label:m,localized_name:k,hasErrors:p,shape:y};i.push(w)}return i}h(xs,"mapSubgraphInputsAndLinks");function As(o,e,t){const n=St(o),i=[];for(const[,s]of n){const a=[];for(const S of s){const{link:E,output:C}=S;if(!C)continue;const I=E.asSerialisable();I.parentId=wn(E,t),I.target_id=-20,I.target_slot=i.length,e.push(I),a.push(I)}const{output:r}=s[0];if(!r)continue;const{color_off:l,color_on:d,dir:u,hasErrors:p,label:m,localized_name:g,name:f,shape:y,type:b}=r,v=He(f,i.map(S=>S.name)),k=g?He(g,i.map(S=>S.localized_name??"")):void 0,w={id:fe(),type:String(b),linkIds:a.map(S=>S.id),name:v,color_off:l,color_on:d,dir:u,label:m,localized_name:k,hasErrors:p,shape:y};i.push(structuredClone(w))}return i}h(As,"mapSubgraphOutputsAndLinks");function Ds(o){const e=new Set;for(const t of o._nodes)t.isSubgraphNode()&&e.add(t.type);return e}h(Ds,"getDirectSubgraphIds");function Os(o,e){const t=new Set,n=[o];for(;n.length>0;){const i=Ds(n.shift());for(const s of i)if(!t.has(s)){t.add(s);const a=e.get(s);a&&n.push(a)}}return t}h(Os,"findUsedSubgraphIds");function Sn(o){return o!=null&&typeof o=="object"&&"parent"in o&&o.parent instanceof Nt}h(Sn,"isSubgraphInput");function In(o){return o!=null&&typeof o=="object"&&"parent"in o&&o.parent instanceof xt}h(In,"isSubgraphOutput");function Cn(o){return o!=null&&typeof o=="object"&&("link"in o||"links"in o)}h(Cn,"isNodeSlot");var Be=class extends _n{static{h(this,"NodeInputSlot")}link;alwaysVisible;get isWidgetInputSlot(){return!!this.widget}#e;get _widget(){return this.#e?.deref()}set _widget(o){this.#e=o?new WeakRef(o):void 0}get collapsedPos(){return[0,_.NODE_TITLE_HEIGHT*-.5]}constructor(o,e){super(o,e),this.link=o.link}get isConnected(){return this.link!=null}isValidTarget(o){return"links"in o?_.isValidConnection(o.type,this.type):Sn(o)?_.isValidConnection(o.type,this.type):!1}draw(o,e){const{textAlign:t}=o;o.textAlign="left",super.draw(o,{...e,labelPosition:tt.Right,doStroke:!1}),o.textAlign=t}},mt=class extends _n{static{h(this,"NodeOutputSlot")}#e;links;_data;slot_index;get isWidgetInputSlot(){return!1}get collapsedPos(){return[this.#e._collapsed_width??_.NODE_COLLAPSED_WIDTH,_.NODE_TITLE_HEIGHT*-.5]}constructor(o,e){super(o,e),this.links=o.links,this._data=o._data,this.slot_index=o.slot_index,this.#e=e}isValidTarget(o){return"link"in o?_.isValidConnection(this.type,o.type):In(o)?_.isValidConnection(this.type,o.type):!1}get isConnected(){return this.links!=null&&this.links.length>0}draw(o,e){const{textAlign:t,strokeStyle:n}=o;o.textAlign="right",o.strokeStyle="black",super.draw(o,{...e,labelPosition:tt.Left,doStroke:!0}),o.textAlign=t,o.strokeStyle=n}},Ps=1e4,Ft=new Set;function Tn(o,e){if(!_.alwaysRepeatWarnings){if(Ft.has(o)||Ft.size>Ps)return;Ft.add(o)}for(const t of _.onDeprecationWarning)t(o,e)}h(Tn,"warnDeprecated");function Ms(o,e){if(e.length===0)return[];const t=e.reduce((s,a)=>s+a.minSize,0);if(o<t)return e.map(s=>s.minSize);let n=e.map(s=>({computedSize:s.minSize,maxSize:s.maxSize??1/0,remaining:(s.maxSize??1/0)-s.minSize})),i=o-t;for(;i>0&&n.some(s=>s.remaining>0);){const s=n.filter(l=>l.remaining>0).length;if(s===0)break;const a=i/s;let r=0;if(n=n.map(l=>{if(l.remaining<=0)return l;const d=Math.min(a,l.remaining);return r+=d,{...l,computedSize:l.computedSize+d,remaining:l.remaining-d}}),i-=r,r===0)break}return n.map(({computedSize:s})=>s)}h(Ms,"distributeSpace");function Rs(o,e,t,n="..."){if(o.measureText(e).width<=t||t<=0)return e;const i=t-o.measureText(n).width;if(i<=0)return n;let s=0,a=e.length,r=0;for(;s<=a;){const l=Math.floor((s+a)/2),d=e.substring(0,l);o.measureText(d).width<=i?(r=l,s=l+1):a=l-1}return e.substring(0,r)+n}h(Rs,"truncateText");const Fs={label:"Open 3D Viewer (Beta) for Selected Node"},zs={label:"Experimental: Browse Model Assets"},Bs={label:"Browse Templates"},Vs={label:"Delete Selected Items"},Us={label:"Fit view to selected nodes"},Ws={label:"Lock Canvas"},Gs={label:"Move Selected Nodes Down"},Hs={label:"Move Selected Nodes Left"},js={label:"Move Selected Nodes Right"},qs={label:"Move Selected Nodes Up"},$s={label:"Reset View"},Ks={label:"Resize Selected Nodes"},Xs={label:"Canvas Toggle Link Visibility"},Ys={label:"Canvas Toggle Lock"},Qs={label:"Canvas Toggle Minimap"},Zs={label:"Pin/Unpin Selected Items"},Js={label:"Bypass/Unbypass Selected Nodes"},ea={label:"Collapse/Expand Selected Nodes"},ta={label:"Mute/Unmute Selected Nodes"},oa={label:"Pin/Unpin Selected Nodes"},na={label:"Unlock Canvas"},ia={label:"Zoom In"},sa={label:"Zoom Out"},aa={label:"Clear Pending Tasks"},ra={label:"Clear Workflow"},la={label:"Contact Support"},da={label:"Show Model Selector (Dev)"},ua={label:"Duplicate Current Workflow"},ca={label:"Export Workflow"},pa={label:"Export Workflow (API Format)"},ma={label:"Convert Selection to Subgraph"},ha={label:"Edit Subgraph Widgets"},ga={label:"Exit Subgraph"},fa={label:"Fit Group To Contents"},_a={label:"Group Selected Nodes"},ya={label:"Toggle promotion of hovered widget"},ba={label:"Unpack the selected Subgraph"},va={label:"Convert selected nodes to group node"},ka={label:"Manage group nodes"},wa={label:"Ungroup selected group nodes"},Sa={label:"Open About ComfyUI"},Ia={label:"Open Comfy-Org Discord"},Ca={label:"Open ComfyUI Docs"},Ta={label:"Open ComfyUI Forum"},La={label:"Open ComfyUI Issues"},Ea={label:"Interrupt"},Na={label:"Load Default Workflow"},xa={label:"Custom Nodes Manager"},Aa={label:"Custom Nodes (Legacy)"},Da={label:"Manager Menu (Legacy)"},Oa={label:"Install Missing Custom Nodes"},Pa={label:"Check for Custom Node Updates"},Ma={label:"Decrease Brush Size in MaskEditor"},Ra={label:"Increase Brush Size in MaskEditor"},Fa={label:"Open Color Picker in MaskEditor"},za={label:"Mirror Horizontal in MaskEditor"},Ba={label:"Mirror Vertical in MaskEditor"},Va={label:"Open Mask Editor for Selected Node"},Ua={label:"Rotate Left in MaskEditor"},Wa={label:"Rotate Right in MaskEditor"},Ga={label:"Unload Models"},Ha={label:"Unload Models and Execution Cache"},ja={label:"New Blank Workflow"},qa={label:"Clipspace"},$a={label:"Manager"},Ka={label:"Open Workflow"},Xa={label:"Publish Subgraph"},Ya={label:"Toggle Job History"},Qa={label:"Queue Prompt"},Za={label:"Queue Prompt (Front)"},Ja={label:"Queue Selected Output Nodes"},er={label:"Redo"},tr={label:"Refresh Node Definitions"},or={label:"Rename Workflow"},nr={label:"Save Workflow"},ir={label:"Save Workflow As"},sr={label:"Show Settings Dialog"},ar={label:"Experimental: Enable AssetAPI"},rr={label:"Canvas Performance"},lr={label:"Help Center"},dr={label:"Toggle Simple Mode"},ur={label:"Toggle Queue Panel V2"},cr={label:"Toggle Theme (Dark/Light)"},pr={label:"Undo"},mr={label:"Open Sign In Dialog"},hr={label:"Sign Out"},gr={label:"Experimental: Enable Nodes 2.0"},fr={label:"Close Current Workflow"},_r={label:"Next Opened Workflow"},yr={label:"Previous Opened Workflow"},br={label:"Toggle Search Box"},vr={label:"Toggle Bottom Panel"},kr={label:"Show Keybindings Dialog"},wr={label:"Toggle Focus Mode"},Sr={label:"Toggle Assets Sidebar",tooltip:"Assets"},Ir={label:"Toggle Workflows Sidebar",tooltip:"Workflows"};var Cr={"Comfy-Desktop_CheckForUpdates":{label:"Check for Updates"},"Comfy-Desktop_Folders_OpenCustomNodesFolder":{label:"Open Custom Nodes Folder"},"Comfy-Desktop_Folders_OpenInputsFolder":{label:"Open Inputs Folder"},"Comfy-Desktop_Folders_OpenLogsFolder":{label:"Open Logs Folder"},"Comfy-Desktop_Folders_OpenModelConfig":{label:"Open extra_model_paths.yaml"},"Comfy-Desktop_Folders_OpenModelsFolder":{label:"Open Models Folder"},"Comfy-Desktop_Folders_OpenOutputsFolder":{label:"Open Outputs Folder"},"Comfy-Desktop_OpenDevTools":{label:"Open DevTools"},"Comfy-Desktop_OpenUserGuide":{label:"Desktop User Guide"},"Comfy-Desktop_Quit":{label:"Quit"},"Comfy-Desktop_Reinstall":{label:"Reinstall"},"Comfy-Desktop_Restart":{label:"Restart"},Comfy_3DViewer_Open3DViewer:Fs,Comfy_BrowseModelAssets:zs,Comfy_BrowseTemplates:Bs,Comfy_Canvas_DeleteSelectedItems:Vs,Comfy_Canvas_FitView:Us,Comfy_Canvas_Lock:Ws,Comfy_Canvas_MoveSelectedNodes_Down:Gs,Comfy_Canvas_MoveSelectedNodes_Left:Hs,Comfy_Canvas_MoveSelectedNodes_Right:js,Comfy_Canvas_MoveSelectedNodes_Up:qs,Comfy_Canvas_ResetView:$s,Comfy_Canvas_Resize:Ks,Comfy_Canvas_ToggleLinkVisibility:Xs,Comfy_Canvas_ToggleLock:Ys,Comfy_Canvas_ToggleMinimap:Qs,Comfy_Canvas_ToggleSelected_Pin:Zs,Comfy_Canvas_ToggleSelectedNodes_Bypass:Js,Comfy_Canvas_ToggleSelectedNodes_Collapse:ea,Comfy_Canvas_ToggleSelectedNodes_Mute:ta,Comfy_Canvas_ToggleSelectedNodes_Pin:oa,Comfy_Canvas_Unlock:na,Comfy_Canvas_ZoomIn:ia,Comfy_Canvas_ZoomOut:sa,Comfy_ClearPendingTasks:aa,Comfy_ClearWorkflow:ra,Comfy_ContactSupport:la,Comfy_Dev_ShowModelSelector:da,Comfy_DuplicateWorkflow:ua,Comfy_ExportWorkflow:ca,Comfy_ExportWorkflowAPI:pa,Comfy_Graph_ConvertToSubgraph:ma,Comfy_Graph_EditSubgraphWidgets:ha,Comfy_Graph_ExitSubgraph:ga,Comfy_Graph_FitGroupToContents:fa,Comfy_Graph_GroupSelectedNodes:_a,Comfy_Graph_ToggleWidgetPromotion:ya,Comfy_Graph_UnpackSubgraph:ba,Comfy_GroupNode_ConvertSelectedNodesToGroupNode:va,Comfy_GroupNode_ManageGroupNodes:ka,Comfy_GroupNode_UngroupSelectedGroupNodes:wa,Comfy_Help_AboutComfyUI:Sa,Comfy_Help_OpenComfyOrgDiscord:Ia,Comfy_Help_OpenComfyUIDocs:Ca,Comfy_Help_OpenComfyUIForum:Ta,Comfy_Help_OpenComfyUIIssues:La,Comfy_Interrupt:Ea,Comfy_LoadDefaultWorkflow:Na,Comfy_Manager_CustomNodesManager_ShowCustomNodesMenu:xa,Comfy_Manager_CustomNodesManager_ShowLegacyCustomNodesMenu:Aa,Comfy_Manager_ShowLegacyManagerMenu:Da,Comfy_Manager_ShowMissingPacks:Oa,Comfy_Manager_ShowUpdateAvailablePacks:Pa,Comfy_MaskEditor_BrushSize_Decrease:Ma,Comfy_MaskEditor_BrushSize_Increase:Ra,Comfy_MaskEditor_ColorPicker:Fa,Comfy_MaskEditor_Mirror_Horizontal:za,Comfy_MaskEditor_Mirror_Vertical:Ba,Comfy_MaskEditor_OpenMaskEditor:Va,Comfy_MaskEditor_Rotate_Left:Ua,Comfy_MaskEditor_Rotate_Right:Wa,Comfy_Memory_UnloadModels:Ga,Comfy_Memory_UnloadModelsAndExecutionCache:Ha,Comfy_NewBlankWorkflow:ja,Comfy_OpenClipspace:qa,Comfy_OpenManagerDialog:$a,Comfy_OpenWorkflow:Ka,Comfy_PublishSubgraph:Xa,Comfy_Queue_ToggleOverlay:Ya,Comfy_QueuePrompt:Qa,Comfy_QueuePromptFront:Za,Comfy_QueueSelectedOutputNodes:Ja,Comfy_Redo:er,Comfy_RefreshNodeDefinitions:tr,Comfy_RenameWorkflow:or,Comfy_SaveWorkflow:nr,Comfy_SaveWorkflowAs:ir,Comfy_ShowSettingsDialog:sr,Comfy_ToggleAssetAPI:ar,Comfy_ToggleCanvasInfo:rr,Comfy_ToggleHelpCenter:lr,Comfy_ToggleLinear:dr,Comfy_ToggleQPOV2:ur,Comfy_ToggleTheme:cr,Comfy_Undo:pr,Comfy_User_OpenSignInDialog:mr,Comfy_User_SignOut:hr,Experimental_ToggleVueNodes:gr,Workspace_CloseWorkflow:fr,Workspace_NextOpenedWorkflow:_r,Workspace_PreviousOpenedWorkflow:yr,Workspace_SearchBox_Toggle:br,Workspace_ToggleBottomPanel:vr,Workspace_ToggleBottomPanel_Shortcuts:kr,"Workspace_ToggleBottomPanelTab_command-terminal":{label:"Toggle Terminal Bottom Panel"},"Workspace_ToggleBottomPanelTab_logs-terminal":{label:"Toggle Logs Bottom Panel"},"Workspace_ToggleBottomPanelTab_shortcuts-essentials":{label:"Toggle Essential Bottom Panel"},"Workspace_ToggleBottomPanelTab_shortcuts-view-controls":{label:"Toggle View Controls Bottom Panel"},Workspace_ToggleFocusMode:wr,Workspace_ToggleSidebarTab_assets:Sr,"Workspace_ToggleSidebarTab_model-library":{label:"Toggle Model Library Sidebar",tooltip:"Model Library"},"Workspace_ToggleSidebarTab_node-library":{label:"Toggle Node Library Sidebar",tooltip:"Node Library"},Workspace_ToggleSidebarTab_workflows:Ir};const Tr={user:"User",currentUser:"Current user",empty:"Empty",noWorkflowsFound:"No workflows found.",comingSoon:"Coming Soon",download:"Download",downloadImage:"Download image",downloadVideo:"Download video",editOrMaskImage:"Edit or mask image",editImage:"Edit image",decrement:"Decrement",deleteImage:"Delete image",deleteAudioFile:"Delete audio file",increment:"Increment",removeImage:"Remove image",removeVideo:"Remove video",removeTag:"Remove tag",chart:"Chart",chartLowercase:"chart",file:"file",selectedFile:"Selected file",none:"None",markdown:"markdown",content:"content",audioProgress:"Audio progress",viewImageOfTotal:"View image {index} of {total}",viewVideoOfTotal:"View video {index} of {total}",imagePreview:"Image preview - Use arrow keys to navigate between images",videoPreview:"Video preview - Use arrow keys to navigate between videos",galleryImage:"Gallery image",galleryThumbnail:"Gallery thumbnail",errorLoadingImage:"Error loading image",errorLoadingVideo:"Error loading video",failedToDownloadImage:"Failed to download image",failedToDownloadVideo:"Failed to download video",calculatingDimensions:"Calculating dimensions",import:"Import",loadAllFolders:"Load All Folders",logoAlt:"ComfyUI Logo",comfyOrgLogoAlt:"ComfyOrg Logo",comfy:"Comfy",refresh:"Refresh",refreshNode:"Refresh Node",vitePreloadErrorTitle:"New Version Available",vitePreloadErrorMessage:`A new version of the app has been released. Would you like to reload?
|
|
@@ -73,8 +73,8 @@ sd3: clip-l, clip-g, t5`,inputs:{clip_name1:{name:"clip_name1"},clip_name2:{name
|
|
|
73
73
|
Helps prevent objects from being unintentionally nudged if the pointer is moved whilst clicking.`},Sk={name:"Pointer click drift (maximum distance)",tooltip:`If the pointer moves more than this distance while holding a button down, it is considered dragging (rather than clicking).
|
|
74
74
|
|
|
75
75
|
Helps prevent objects from being unintentionally nudged if the pointer is moved whilst clicking.`},Ik={name:"Double click interval (maximum)",tooltip:"The maximum time in milliseconds between the two clicks of a double-click. Increasing this value may assist if double-clicks are sometimes not registered."},Ck={name:"Preview image format",tooltip:"When displaying a preview in the image widget, convert it to a lightweight image, e.g. webp, jpeg, webp;50, etc."},Tk={name:"Prompt for filename when saving workflow"},Lk={name:"Queue history size",tooltip:"The maximum number of tasks that show in the queue history."},Ek={name:"Use the unified job queue in the Assets side panel",tooltip:"Replaces the floating job queue panel with an equivalent job queue embedded in the Assets side panel. You can disable this to return to the floating panel layout."},Nk={name:"Batch count limit",tooltip:"The maximum number of tasks added to the queue at one button click"},xk={name:"Sidebar location",options:{left:"left",right:"right"}},Ak={name:"Sidebar size",options:{normal:"normal",small:"small"}},Dk={name:"Sidebar style",options:{floating:"floating",connected:"connected"}},Ok={name:"Unified sidebar width"},Pk={name:"Snap to grid size",tooltip:"When dragging and resizing nodes while holding shift they will be aligned to the grid, this controls the size of that grid."},Mk={name:"Textarea widget font size"},Rk={name:"Textarea widget spellcheck"},Fk={name:"Tree explorer item padding"},zk={name:"Tab Bar Layout",tooltip:'Controls the layout of the tab bar. "Integrated" moves Help and User controls into the tab bar area.',options:{Default:"Default",Integrated:"Integrated"}},Bk={name:"Use new menu",tooltip:"Enable the redesigned top menu bar.",options:{Disabled:"Disabled",Top:"Top"}},Vk={name:"Validate workflows"},Uk={name:"Auto-scale layout (Nodes 2.0)",tooltip:"Automatically scale node positions when switching to Nodes 2.0 rendering to prevent overlap"},Wk={name:"Modern Node Design (Nodes 2.0)",tooltip:"Modern: DOM-based rendering with enhanced interactivity, native browser features, and updated visual design. Classic: Traditional canvas rendering."},Gk={name:"Widget control mode",tooltip:"Controls when widget values are updated (randomize/increment/decrement), either before the prompt is queued or after.",options:{before:"before",after:"after"}},Hk={name:"Show confirmation when closing window"},jk={name:"Auto Save",options:{off:"off","after delay":"after delay"}},qk={name:"Auto Save Delay (ms)",tooltip:'Only applies if Auto Save is set to "after delay".'},$k={name:"Show confirmation when deleting workflows"},Kk={name:"Persist workflow state and restore on page (re)load"},Xk={name:"Show missing models warning"},Yk={name:"Show missing nodes warning"},Qk={name:"Sort node IDs when saving workflow"},Zk={name:"Require confirmation to overwrite an existing subgraph blueprint"},Jk={name:"Opened workflows position",options:{Sidebar:"Sidebar",Topbar:"Topbar"}},ew={name:"Maximum FPS",tooltip:"The maximum frames per second that the canvas is allowed to render. Caps GPU usage at the cost of smoothness. If 0, the screen refresh rate is used. Default: 0"},tw={name:"Zoom Node Level of Detail - font size threshold",tooltip:"Controls when the nodes switch to low quality LOD rendering. Uses font size in pixels to determine when to switch. Set to 0 to disable. Values 1-24 set the minimum font size threshold for LOD - higher values (24px) = switch nodes to simplified rendering sooner when zooming out, lower values (1px) = maintain full node quality longer."},ow={name:"Scale node combo widget menus (lists) when zoomed in"},nw={name:"Always shrink new nodes",tooltip:"Resize nodes to the smallest possible size when created. When disabled, a newly added node will be widened slightly to show widget values."},iw={name:"Tooltip Delay"},sw={name:"Reroute spline offset",tooltip:"The bezier control point offset from the reroute centre point"},aw={name:"Always snap to grid"};var rw={"Comfy-Desktop_AutoUpdate":{name:"Automatically check for updates"},"Comfy-Desktop_SendStatistics":{name:"Send anonymous usage metrics"},"Comfy-Desktop_UV_PypiInstallMirror":{name:"Pypi Install Mirror",tooltip:"Default pip install mirror"},"Comfy-Desktop_UV_PythonInstallMirror":{name:"Python Install Mirror",tooltip:"Managed Python installations are downloaded from the Astral python-build-standalone project. This variable can be set to a mirror URL to use a different source for Python installations. The provided URL will replace https://github.com/astral-sh/python-build-standalone/releases/download in, e.g., https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-aarch64-apple-darwin-install_only.tar.gz. Distributions can be read from a local directory by using the file:// URL scheme."},"Comfy-Desktop_UV_TorchInstallMirror":{name:"Torch Install Mirror",tooltip:"Pip install mirror for pytorch"},"Comfy-Desktop_WindowStyle":{name:"Window Style",tooltip:"Custom: Replace the system title bar with ComfyUI's Top menu",options:{default:"default",custom:"custom"}},Comfy_Canvas_BackgroundImage:fv,Comfy_Canvas_LeftMouseClickBehavior:_v,Comfy_Canvas_MouseWheelScroll:yv,Comfy_Canvas_NavigationMode:bv,Comfy_Canvas_SelectionToolbox:vv,Comfy_ConfirmClear:kv,Comfy_DevMode:wv,Comfy_DisableFloatRounding:Sv,Comfy_DisableSliders:Iv,Comfy_DOMClippingEnabled:Cv,Comfy_EditAttention_Delta:Tv,Comfy_EnableTooltips:Lv,Comfy_EnableWorkflowViewRestore:Ev,Comfy_Execution_PreviewMethod:Nv,Comfy_FloatRoundingPrecision:xv,Comfy_Graph_CanvasInfo:Av,Comfy_Graph_CanvasMenu:Dv,Comfy_Graph_CtrlShiftZoom:Ov,Comfy_Graph_LinkMarkers:Pv,Comfy_Graph_LiveSelection:Mv,Comfy_Graph_ZoomSpeed:Rv,Comfy_Group_DoubleClickTitleToEdit:Fv,Comfy_GroupSelectedNodes_Padding:zv,Comfy_LinkRelease_Action:Bv,Comfy_LinkRelease_ActionShift:Vv,Comfy_LinkRenderMode:Uv,Comfy_Load3D_3DViewerEnable:Wv,Comfy_Load3D_BackgroundColor:Gv,Comfy_Load3D_CameraType:Hv,Comfy_Load3D_LightAdjustmentIncrement:jv,Comfy_Load3D_LightIntensity:qv,Comfy_Load3D_LightIntensityMaximum:$v,Comfy_Load3D_LightIntensityMinimum:Kv,Comfy_Load3D_PLYEngine:Xv,Comfy_Load3D_ShowGrid:Yv,Comfy_Locale:Qv,Comfy_MaskEditor_BrushAdjustmentSpeed:Zv,Comfy_MaskEditor_UseDominantAxis:Jv,Comfy_ModelLibrary_AutoLoadAll:ek,Comfy_ModelLibrary_NameFormat:tk,Comfy_Node_AllowImageSizeDraw:ok,Comfy_Node_AutoSnapLinkToSlot:nk,Comfy_Node_BypassAllLinksOnDelete:ik,Comfy_Node_DoubleClickTitleToEdit:sk,Comfy_Node_MiddleClickRerouteNode:ak,Comfy_Node_Opacity:rk,Comfy_Node_ShowDeprecated:lk,Comfy_Node_ShowExperimental:dk,Comfy_Node_SnapHighlightsNode:uk,Comfy_NodeBadge_NodeIdBadgeMode:ck,Comfy_NodeBadge_NodeLifeCycleBadgeMode:pk,Comfy_NodeBadge_NodeSourceBadgeMode:mk,Comfy_NodeBadge_ShowApiPricing:hk,Comfy_NodeSearchBoxImpl:gk,Comfy_NodeSearchBoxImpl_NodePreview:fk,Comfy_NodeSearchBoxImpl_ShowCategory:_k,Comfy_NodeSearchBoxImpl_ShowIdName:yk,Comfy_NodeSearchBoxImpl_ShowNodeFrequency:bk,Comfy_NodeSuggestions_number:vk,Comfy_Notification_ShowVersionUpdates:kk,Comfy_Pointer_ClickBufferTime:wk,Comfy_Pointer_ClickDrift:Sk,Comfy_Pointer_DoubleClickTime:Ik,Comfy_PreviewFormat:Ck,Comfy_PromptFilename:Tk,Comfy_Queue_MaxHistoryItems:Lk,Comfy_Queue_QPOV2:Ek,Comfy_QueueButton_BatchCountLimit:Nk,Comfy_Sidebar_Location:xk,Comfy_Sidebar_Size:Ak,Comfy_Sidebar_Style:Dk,Comfy_Sidebar_UnifiedWidth:Ok,Comfy_SnapToGrid_GridSize:Pk,Comfy_TextareaWidget_FontSize:Mk,Comfy_TextareaWidget_Spellcheck:Rk,Comfy_TreeExplorer_ItemPadding:Fk,Comfy_UI_TabBarLayout:zk,Comfy_UseNewMenu:Bk,Comfy_Validation_Workflows:Vk,Comfy_VueNodes_AutoScaleLayout:Uk,Comfy_VueNodes_Enabled:Wk,Comfy_WidgetControlMode:Gk,Comfy_Window_UnloadConfirmation:Hk,Comfy_Workflow_AutoSave:jk,Comfy_Workflow_AutoSaveDelay:qk,Comfy_Workflow_ConfirmDelete:$k,Comfy_Workflow_Persist:Kk,Comfy_Workflow_ShowMissingModelsWarning:Xk,Comfy_Workflow_ShowMissingNodesWarning:Yk,Comfy_Workflow_SortNodeIdOnSave:Qk,Comfy_Workflow_WarnBlueprintOverwrite:Zk,Comfy_Workflow_WorkflowTabsPosition:Jk,LiteGraph_Canvas_MaximumFps:ew,LiteGraph_Canvas_MinFontSizeForLOD:tw,LiteGraph_ContextMenu_Scaling:ow,LiteGraph_Node_DefaultPadding:nw,LiteGraph_Node_TooltipDelay:iw,LiteGraph_Reroute_SplineOffset:sw,pysssss_SnapToGrid:aw};function Ln(o,e,t,n){return{...o,nodeDefs:e,commands:t,settings:n}}h(Ln,"buildLocale");var lw={ar:h(()=>R(()=>import("./main-Ctu0kOup.js"),[],import.meta.url),"ar"),es:h(()=>R(()=>import("./main-T_GYGdF4.js"),[],import.meta.url),"es"),fa:h(()=>R(()=>import("./main-BfuU7qSf.js"),[],import.meta.url),"fa"),fr:h(()=>R(()=>import("./main-C0e9JuPP.js"),[],import.meta.url),"fr"),ja:h(()=>R(()=>import("./main-DcQJjsuE.js"),[],import.meta.url),"ja"),ko:h(()=>R(()=>import("./main-Bpj4Ol1p.js"),[],import.meta.url),"ko"),ru:h(()=>R(()=>import("./main-CidiGVb5.js"),[],import.meta.url),"ru"),tr:h(()=>R(()=>import("./main-C0im_Y2_.js"),[],import.meta.url),"tr"),zh:h(()=>R(()=>import("./main-CenoxCsP.js"),[],import.meta.url),"zh"),"zh-TW":h(()=>R(()=>import("./main-B7OAVIPi.js"),[],import.meta.url),"zh-TW"),"pt-BR":h(()=>R(()=>import("./main-DHiBZ8hT.js"),[],import.meta.url),"pt-BR")},dw={ar:h(()=>R(()=>import("./nodeDefs-4C2SCsNS.js"),[],import.meta.url),"ar"),es:h(()=>R(()=>import("./nodeDefs-BqSY8Xg8.js"),[],import.meta.url),"es"),fa:h(()=>R(()=>import("./nodeDefs-C8z5Iobp.js"),[],import.meta.url),"fa"),fr:h(()=>R(()=>import("./nodeDefs-CjyrmyWu.js"),[],import.meta.url),"fr"),ja:h(()=>R(()=>import("./nodeDefs-dfDqD8cp.js"),[],import.meta.url),"ja"),ko:h(()=>R(()=>import("./nodeDefs-BfcpV6di.js"),[],import.meta.url),"ko"),ru:h(()=>R(()=>import("./nodeDefs-BuuJ35aV.js"),[],import.meta.url),"ru"),tr:h(()=>R(()=>import("./nodeDefs-CFn2GD2L.js"),[],import.meta.url),"tr"),zh:h(()=>R(()=>import("./nodeDefs-Dg2JwX-7.js"),[],import.meta.url),"zh"),"zh-TW":h(()=>R(()=>import("./nodeDefs-ByjyObAC.js"),[],import.meta.url),"zh-TW"),"pt-BR":h(()=>R(()=>import("./nodeDefs-DfpniSom.js"),[],import.meta.url),"pt-BR")},uw={ar:h(()=>R(()=>import("./commands-ALHJUtBt.js"),[],import.meta.url),"ar"),es:h(()=>R(()=>import("./commands-nBvAv4ZK.js"),[],import.meta.url),"es"),fa:h(()=>R(()=>import("./commands-BHUkyfRw.js"),[],import.meta.url),"fa"),fr:h(()=>R(()=>import("./commands-FbRpbULE.js"),[],import.meta.url),"fr"),ja:h(()=>R(()=>import("./commands-BSIJGghA.js"),[],import.meta.url),"ja"),ko:h(()=>R(()=>import("./commands-lkD8qVC6.js"),[],import.meta.url),"ko"),ru:h(()=>R(()=>import("./commands-CWJmJKXb.js"),[],import.meta.url),"ru"),tr:h(()=>R(()=>import("./commands-rSJXy9H0.js"),[],import.meta.url),"tr"),zh:h(()=>R(()=>import("./commands-DITj6w74.js"),[],import.meta.url),"zh"),"zh-TW":h(()=>R(()=>import("./commands-B34CPJTq.js"),[],import.meta.url),"zh-TW"),"pt-BR":h(()=>R(()=>import("./commands-BMnxQlh7.js"),[],import.meta.url),"pt-BR")},cw={ar:h(()=>R(()=>import("./settings-DkHpHyGj.js"),[],import.meta.url),"ar"),es:h(()=>R(()=>import("./settings-DTnHLLAV.js"),[],import.meta.url),"es"),fa:h(()=>R(()=>import("./settings-D0zIF35-.js"),[],import.meta.url),"fa"),fr:h(()=>R(()=>import("./settings-BX2BMwI7.js"),[],import.meta.url),"fr"),ja:h(()=>R(()=>import("./settings-B0dfKMEa.js"),[],import.meta.url),"ja"),ko:h(()=>R(()=>import("./settings-Bw1gshdG.js"),[],import.meta.url),"ko"),ru:h(()=>R(()=>import("./settings-Bw3LK7Y8.js"),[],import.meta.url),"ru"),tr:h(()=>R(()=>import("./settings-Dtdx67Ca.js"),[],import.meta.url),"tr"),zh:h(()=>R(()=>import("./settings-CLLR_wSs.js"),[],import.meta.url),"zh"),"zh-TW":h(()=>R(()=>import("./settings-Xr9KTSkm.js"),[],import.meta.url),"zh-TW"),"pt-BR":h(()=>R(()=>import("./settings-BgCICp5V.js"),[],import.meta.url),"pt-BR")},Yt=new Set(["en"]),zt=new Map,Je={};async function YS(o){if(Yt.has(o))return;const e=zt.get(o);if(e)return e;const t=lw[o],n=dw[o],i=uw[o],s=cw[o];if(!t||!n||!i||!s){console.warn(`Locale "${o}" is not supported`);return}const a=(async()=>{try{const[r,l,d,u]=await Promise.all([t(),n(),i(),s()]),p=Ln(r.default,l.default,d.default,u.default);It.global.setLocaleMessage(o,p),Yt.add(o),Je[o]&&It.global.mergeLocaleMessage(o,Je[o])}catch(r){throw console.error(`Failed to load locale "${o}":`,r),r}finally{zt.delete(o)}})();return zt.set(o,a),a}h(YS,"loadLocale");function QS(o){for(const e of Object.keys(Je))delete Je[e];Object.assign(Je,o);for(const[e,t]of Object.entries(o))Yt.has(e)&&It.global.mergeLocaleMessage(e,t)}h(QS,"mergeCustomNodesI18n");var pw={en:Ln(Ld,gv,Cr,rw)};const It=li({legacy:!1,locale:navigator.language.split("-")[0]||"en",fallbackLocale:"en",escapeParameter:!0,messages:pw,missingWarn:/^(?!settings\.Comfy_Locale\.options\.).+/,fallbackWarn:/^(?!settings\.Comfy_Locale\.options\.).+/}),{t:ye,te:mw,d:ZS}=It.global;function JS(o,e){return mw(o)?ye(o):e}h(JS,"st");var B=class ht{static{h(this,"BaseWidget")}static margin=15;static arrowMargin=6;static arrowWidth=10;static minValueWidth=42;static labelValueGap=5;#e;get node(){return this.#e}linkedWidgets;name;options;label;type;y=0;last_y;width;disabled;computedDisabled;hidden;advanced;promoted;tooltip;element;#t;get value(){return this.#t}set value(e){this.#t=e}constructor(e,t){this.#e=t??e.node,this.name=e.name,this.options=e.options,this.type=e.type;const{node:n,outline_color:i,background_color:s,height:a,text_color:r,secondary_text_color:l,disabledTextColor:d,displayName:u,displayValue:p,labelBaseline:m,promoted:g,...f}=e;Object.assign(this,f)}get outline_color(){return this.promoted?_.WIDGET_PROMOTED_OUTLINE_COLOR:this.advanced?_.WIDGET_ADVANCED_OUTLINE_COLOR:_.WIDGET_OUTLINE_COLOR}get background_color(){return _.WIDGET_BGCOLOR}get height(){return _.NODE_WIDGET_HEIGHT}get text_color(){return _.WIDGET_TEXT_COLOR}get secondary_text_color(){return _.WIDGET_SECONDARY_TEXT_COLOR}get disabledTextColor(){return _.WIDGET_DISABLED_TEXT_COLOR}get displayName(){return this.label||this.name}get _displayValue(){return this.computedDisabled?"":String(this.value)}get labelBaseline(){return this.y+this.height*.7}drawWidgetShape(e,{width:t,showText:n}){const{height:i,y:s}=this,{margin:a}=ht;e.textAlign="left",e.strokeStyle=this.outline_color,e.fillStyle=this.background_color,e.beginPath(),n?e.roundRect(a,s,t-a*2,i,[i*.5]):e.rect(a,s,t-a*2,i),e.fill(),n&&!this.computedDisabled&&e.stroke()}drawVueOnlyWarning(e,{width:t},n){const{y:i,height:s}=this;e.save(),e.fillStyle=this.background_color,e.fillRect(15,i,t-30,s),e.strokeStyle=this.outline_color,e.strokeRect(15,i,t-30,s),e.fillStyle=this.text_color,e.font="11px monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(`${n}: ${ye("widgets.node2only")}`,t/2,i+s/2),e.restore()}drawTruncatingText({ctx:e,width:t,leftPadding:n=5,rightPadding:i=20}){const{height:s,y:a}=this,{margin:r}=ht,{displayName:l,_displayValue:d}=this,u=e.measureText(l).width,p=e.measureText(d).width,m=ht.labelValueGap,g=r*2+n,f=t-g-2*r-i,y=u+m+p,b=new X(g,a,f,s*.7);if(e.fillStyle=this.secondary_text_color,y<=f)qe({ctx:e,text:l,area:b,align:"left"});else if(_.truncateWidgetTextEvenly){const v=(f-m)/(y-m);b.width=u*v,qe({ctx:e,text:l,area:b,align:"left"}),b.right=g+f,b.setWidthRightAnchored(p*v)}else if(_.truncateWidgetValuesFirst){const v=Math.min(u,f);b.width=v,qe({ctx:e,text:l,area:b,align:"left"}),b.right=g+f,b.setWidthRightAnchored(Math.max(f-m-v,0))}else{const v=Math.min(p,f);b.width=Math.max(f-m-v,0),qe({ctx:e,text:l,area:b,align:"left"}),b.right=g+f,b.setWidthRightAnchored(v)}e.fillStyle=this.text_color,qe({ctx:e,text:d,area:b,align:"right"})}setValue(e,{e:t,node:n,canvas:i}){const s=this.value;if(e===this.value)return;const a=this.type==="number"?Number(e):e;this.value=a,this.options?.property&&n.properties[this.options.property]!==void 0&&n.setProperty(this.options.property,a);const r=i.graph_mouse;this.callback?.(this.value,i,n,r,t),n.onWidgetChanged?.(this.name??"",a,s,this),n.graph&&n.graph._version++}createCopyForNode(e){const t=new this.constructor(this,e);return t.value=this.value,t}},En=class extends B{static{h(this,"AssetWidget")}constructor(o,e){super(o,e),this.type??="asset",this.value=o.value?.toString()??""}set value(o){const e=this.value;if(super.value=o,e!==o&&this.node.graph?.list_of_graphcanvas)for(const t of this.node.graph.list_of_graphcanvas)t.setDirty(!0)}get value(){return super.value}get _displayValue(){return String(this.value)}drawWidget(o,{width:e,showText:t=!0}){const{fillStyle:n,strokeStyle:i,textAlign:s}=o;this.drawWidgetShape(o,{width:e,showText:t}),t&&this.drawTruncatingText({ctx:o,width:e,leftPadding:0,rightPadding:0}),Object.assign(o,{textAlign:s,strokeStyle:i,fillStyle:n})}onClick(){this.options.openModal(this)}},hw=class extends B{static{h(this,"BooleanWidget")}type="toggle";drawWidget(o,{width:e,showText:t=!0}){const{height:n,y:i}=this,{margin:s}=B;this.drawWidgetShape(o,{width:e,showText:t}),o.fillStyle=this.value?"#89A":"#333",o.beginPath(),o.arc(e-s*2,i+n*.5,n*.36,0,Math.PI*2),o.fill(),t&&(this.drawLabel(o,s*2),this.drawValue(o,e-40))}drawLabel(o,e){o.fillStyle=this.secondary_text_color;const{displayName:t}=this;t&&o.fillText(t,e,this.labelBaseline)}drawValue(o,e){o.fillStyle=this.value?this.text_color:this.secondary_text_color,o.textAlign="right";const t=this.value?this.options.on||"true":this.options.off||"false";o.fillText(t,e,this.labelBaseline)}onClick(o){this.setValue(!this.value,o)}},gw=class extends B{static{h(this,"BoundingBoxWidget")}type="boundingbox";drawWidget(o,e){this.drawVueOnlyWarning(o,e,"BoundingBox")}onClick(o){}},fw=class extends B{static{h(this,"ButtonWidget")}type="button";clicked;constructor(o,e){super(o,e),this.clicked??=!1}drawWidget(o,{width:e,showText:t=!0}){const{fillStyle:n,strokeStyle:i,textAlign:s}=o,{height:a,y:r}=this,{margin:l}=B;o.fillStyle=this.background_color,this.clicked&&(o.fillStyle="#AAA",this.clicked=!1),o.fillRect(l,r,e-l*2,a),t&&!this.computedDisabled&&(o.strokeStyle=this.outline_color,o.strokeRect(l,r,e-l*2,a)),t&&this.drawLabel(o,e*.5),Object.assign(o,{textAlign:s,strokeStyle:i,fillStyle:n})}drawLabel(o,e){o.textAlign="center",o.fillStyle=this.text_color,o.fillText(this.displayName,e,this.y+this.height*.7)}onClick({e:o,node:e,canvas:t}){const n=t.graph_mouse;this.clicked=!0,t.setDirty(!0),this.callback?.(this.value,t,e,n,o)}},_w=class extends B{static{h(this,"ChartWidget")}type="chart";drawWidget(o,e){const{width:t}=e,{y:n,height:i}=this,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d}=o;o.fillStyle=this.background_color,o.fillRect(15,n,t-30,i),o.strokeStyle=this.outline_color,o.strokeRect(15,n,t-30,i),o.fillStyle=this.text_color,o.font="11px monospace",o.textAlign="center",o.textBaseline="middle";const u=`Chart: ${ye("widgets.node2only")}`;o.fillText(u,t/2,n+i/2),Object.assign(o,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d})}onClick(o){}},yw=class extends B{static{h(this,"ColorWidget")}type="color";drawWidget(o,e){const{width:t}=e,{y:n,height:i}=this,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d}=o;o.fillStyle=this.background_color,o.fillRect(15,n,t-30,i),o.strokeStyle=this.outline_color,o.strokeRect(15,n,t-30,i),o.fillStyle=this.text_color,o.font="11px monospace",o.textAlign="center",o.textBaseline="middle";const u=`Color: ${ye("widgets.node2only")}`;o.fillText(u,t/2,n+i/2),Object.assign(o,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d})}onClick(o){}},Nn=class extends B{static{h(this,"BaseSteppedWidget")}drawArrowButtons(o,e){const{height:t,text_color:n,disabledTextColor:i,y:s}=this,{arrowMargin:a,arrowWidth:r,margin:l}=B,d=l+a,u=d+r;o.fillStyle=this.canDecrement()?n:i,o.beginPath(),o.moveTo(u,s+5),o.lineTo(d,s+t*.5),o.lineTo(u,s+t-5),o.fill(),o.fillStyle=this.canIncrement()?n:i,o.beginPath(),o.moveTo(e-u,s+5),o.lineTo(e-d,s+t*.5),o.lineTo(e-u,s+t-5),o.fill()}drawWidget(o,e){const{fillStyle:t,strokeStyle:n,textAlign:i}=o;this.drawWidgetShape(o,e),e.showText&&(this.computedDisabled||this.drawArrowButtons(o,e.width),this.drawTruncatingText({ctx:o,width:e.width})),Object.assign(o,{textAlign:i,strokeStyle:n,fillStyle:t})}};function Bt(o){return Array.isArray(o)?o:Object.keys(o)}h(Bt,"toArray");var bw=class extends Nn{static{h(this,"ComboWidget")}type="combo";get _displayValue(){if(this.computedDisabled)return"";if(this.options.getOptionLabel)try{return this.options.getOptionLabel(this.value?String(this.value):null)}catch(e){return console.error("Failed to map value:",e),this.value?String(this.value):""}const{values:o}=this.options;if(o){const e=typeof o=="function"?o():o;if(e&&!Array.isArray(e))return e[this.value]}return typeof this.value=="number"?String(this.value):this.value}getValues(o){const{values:e}=this.options;if(e==null)throw new Error("[ComboWidget]: values is required");return typeof e=="function"?e(this,o):e}canUseButton(o){const{values:e}=this.options;if(typeof e=="function")return!1;const t=Bt(e);if(!(t.length>1))return!1;const n=t.at(0),i=t.at(-1);return n===i?!0:this.value!==(o?i:n)}canIncrement(){return this.canUseButton(!0)}canDecrement(){return this.canUseButton(!1)}incrementValue(o){this.tryChangeValue(1,o)}decrementValue(o){this.tryChangeValue(-1,o)}tryChangeValue(o,e){const t=this.getValues(e.node),n=Bt(t);e.canvas.last_mouseclick=0;const i=pe(typeof t=="object"?n.indexOf(String(this.value))+o:n.indexOf(this.value)+o,0,n.length-1),s=Array.isArray(t)?t[i]:i;this.setValue(s,e)}onClick({e:o,node:e,canvas:t}){const n=o.canvasX-e.pos[0],i=this.width||e.size[0];if(typeof this.options.values=="function"&&Tn("Using a function for values is deprecated. Use an array of unique values instead."),n<40)return this.decrementValue({e:o,node:e,canvas:t});if(n>i-40)return this.incrementValue({e:o,node:e,canvas:t});const s=this.getValues(e),a=Bt(s);if(this.options.getOptionLabel){const l={scale:Math.max(1,t.ds.scale),event:o,className:"dark",callback:h(u=>{this.setValue(u,{e:o,node:e,canvas:t})},"callback")},d=new _.ContextMenu([],l);for(const u of a)try{const p=this.options.getOptionLabel(String(u));d.addItem(p,u,l)}catch(p){console.error("Failed to map value:",p),d.addItem(String(u),u,l)}return}const r=s!=a?Object.values(s):s;new _.ContextMenu(r,{scale:Math.max(1,t.ds.scale),event:o,className:"dark",callback:h(l=>{this.setValue(s!=a?r.indexOf(l):l,{e:o,node:e,canvas:t})},"callback")})}},vw=class extends B{static{h(this,"FileUploadWidget")}type="fileupload";drawWidget(o,e){const{width:t}=e,{y:n,height:i}=this,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d}=o;o.fillStyle=this.background_color,o.fillRect(15,n,t-30,i),o.strokeStyle=this.outline_color,o.strokeRect(15,n,t-30,i),o.fillStyle=this.text_color,o.font="11px monospace",o.textAlign="center",o.textBaseline="middle";const u=`Fileupload: ${ye("widgets.node2only")}`;o.fillText(u,t/2,n+i/2),Object.assign(o,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d})}onClick(o){}},kw=class extends B{static{h(this,"GalleriaWidget")}type="galleria";drawWidget(o,e){const{width:t}=e,{y:n,height:i}=this,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d}=o;o.fillStyle=this.background_color,o.fillRect(15,n,t-30,i),o.strokeStyle=this.outline_color,o.strokeRect(15,n,t-30,i),o.fillStyle=this.text_color,o.font="11px monospace",o.textAlign="center",o.textBaseline="middle";const u=`Galleria: ${ye("widgets.node2only")}`;o.fillText(u,t/2,n+i/2),Object.assign(o,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d})}onClick(o){}},ww=class extends B{static{h(this,"ImageCompareWidget")}type="imagecompare";drawWidget(o,e){const{width:t}=e,{y:n,height:i}=this,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d}=o;o.fillStyle=this.background_color,o.fillRect(15,n,t-30,i),o.strokeStyle=this.outline_color,o.strokeRect(15,n,t-30,i),o.fillStyle=this.text_color,o.font="11px monospace",o.textAlign="center",o.textBaseline="middle";const u=`ImageCompare: ${ye("widgets.node2only")}`;o.fillText(u,t/2,n+i/2),Object.assign(o,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d})}onClick(o){}},Sw=class extends B{static{h(this,"ImageCropWidget")}type="imagecrop";drawWidget(o,e){this.drawVueOnlyWarning(o,e,"ImageCrop")}onClick(o){}},Iw=class extends B{static{h(this,"KnobWidget")}type="knob";computeLayoutSize(){return{minHeight:60,minWidth:20,maxHeight:1e6,maxWidth:1e6}}get height(){return this.computedHeight||super.height}drawWidget(o,{width:e,showText:t=!0}){const{fillStyle:n,strokeStyle:i,textAlign:s}=o,{y:a}=this,{margin:r}=B,{gradient_stops:l="rgb(14, 182, 201); rgb(0, 216, 72)"}=this.options,d=this.computedHeight||this.height,u=Math.min(this.computedHeight||this.height,this.width||20)/20,p={x:e/2,y:d/2+a};o.lineWidth=(Math.min(e,d)-r*u)/6;const m=(Math.min(e,d)-r*u-o.lineWidth)/2;{const w=o.createRadialGradient(p.x,p.y,m+o.lineWidth,0,0,m+o.lineWidth);w.addColorStop(0,"rgb(29, 29, 29)"),w.addColorStop(1,"rgb(116, 116, 116)"),o.fillStyle=w}o.beginPath(),o.arc(p.x,p.y,m+o.lineWidth/2,0,Math.PI*2,!1),o.fill(),o.closePath();const g={start_angle:Math.PI*.6,end_angle:Math.PI*2.4};o.beginPath();{const w=o.createRadialGradient(p.x,p.y,m+o.lineWidth,0,0,m+o.lineWidth);w.addColorStop(0,"rgb(99, 99, 99)"),w.addColorStop(1,"rgb(36, 36, 36)"),o.strokeStyle=w}o.arc(p.x,p.y,m,g.start_angle,g.end_angle,!1),o.stroke(),o.closePath();const f=this.options.max-this.options.min;let y=(this.value-this.options.min)/f;y=pe(y,0,1),o.beginPath();const b=o.createConicGradient(g.start_angle,p.x,p.y),v=l.split(";");for(const[w,S]of v.entries())b.addColorStop(w,S.trim());o.strokeStyle=b;const k=(g.end_angle-g.start_angle)*y+g.start_angle;if(o.arc(p.x,p.y,m,g.start_angle,k,!1),o.stroke(),o.closePath(),t&&!this.computedDisabled&&(o.strokeStyle=this.outline_color,o.beginPath(),o.strokeStyle=this.outline_color,o.arc(p.x,p.y,m+o.lineWidth/2,0,Math.PI*2,!1),o.lineWidth=1,o.stroke(),o.closePath()),t){o.textAlign="center",o.fillStyle=this.text_color;const w=Number(this.value).toFixed(this.options.precision??3);o.fillText(`${this.label||this.name}
|
|
76
|
-
${w}`,e*.5,a+d*.5)}Object.assign(o,{textAlign:s,strokeStyle:i,fillStyle:n})}onClick(){this.current_drag_offset=0}current_drag_offset=0;onDrag(o){if(this.options.read_only)return;const{e}=o,t=Ke(this.options),n=this.options.max-this.options.min,i=n/10,s=n/100,a={delta_x:t,shift:i>t?i-i%t:t,delta_y:s>t?s-s%t:t},r=Math.abs(e.movementY)>Math.abs(e.movementX),l=r?-e.movementY:e.movementX,d=15;this.current_drag_offset+=l;let u=0;this.current_drag_offset>d?(u+=1,this.current_drag_offset-=d):this.current_drag_offset<-d&&(u-=1,this.current_drag_offset+=d);const p=e.shiftKey?a.shift:r?a.delta_y:t,m=u*p,g=pe(this.value+m,this.options.min,this.options.max);g!==this.value&&this.setValue(g,o)}},Cw=class extends B{static{h(this,"LegacyWidget")}drawWidget(o,e){const t=_.NODE_WIDGET_HEIGHT;this.draw?.(o,this.node,e.width,this.y,t,!!e.showText)}onClick(){console.warn("Custom widget wrapper onClick was just called. Handling for third party widgets is done via LGraphCanvas - the mouse callback.")}},Tw=class extends B{static{h(this,"MarkdownWidget")}type="markdown";drawWidget(o,e){const{width:t}=e,{y:n,height:i}=this,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d}=o;o.fillStyle=this.background_color,o.fillRect(15,n,t-30,i),o.strokeStyle=this.outline_color,o.strokeRect(15,n,t-30,i),o.fillStyle=this.text_color,o.font="11px monospace",o.textAlign="center",o.textBaseline="middle";const u=`Markdown: ${ye("widgets.node2only")}`;o.fillText(u,t/2,n+i/2),Object.assign(o,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d})}onClick(o){}},Lw=class extends B{static{h(this,"MultiSelectWidget")}type="multiselect";drawWidget(o,e){const{width:t}=e,{y:n,height:i}=this,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d}=o;o.fillStyle=this.background_color,o.fillRect(15,n,t-30,i),o.strokeStyle=this.outline_color,o.strokeRect(15,n,t-30,i),o.fillStyle=this.text_color,o.font="11px monospace",o.textAlign="center",o.textBaseline="middle";const u=`MultiSelect: ${ye("widgets.node2only")}`;o.fillText(u,t/2,n+i/2),Object.assign(o,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d})}onClick(o){}},Ew=class extends Nn{static{h(this,"NumberWidget")}type="number";get _displayValue(){return this.computedDisabled?"":Number(this.value).toFixed(this.options.precision!==void 0?this.options.precision:3)}canIncrement(){const{max:o}=this.options;return o==null||this.value<o}canDecrement(){const{min:o}=this.options;return o==null||this.value>o}incrementValue(o){this.setValue(this.value+Ke(this.options),o)}decrementValue(o){this.setValue(this.value-Ke(this.options),o)}setValue(o,e){let t=o;this.options.min!=null&&t<this.options.min&&(t=this.options.min),this.options.max!=null&&t>this.options.max&&(t=this.options.max),super.setValue(t,e)}onClick({e:o,node:e,canvas:t}){const n=o.canvasX-e.pos[0],i=this.width||e.size[0],s=n<40?-1:n>i-40?1:0;if(s){this.setValue(this.value+s*Ke(this.options),{e:o,node:e,canvas:t});return}t.prompt("Value",this.value,a=>{const r=di(a);r!==void 0&&this.setValue(r,{e:o,node:e,canvas:t})},o)}onDrag({e:o,node:e,canvas:t}){const n=this.width||e.width,i=o.canvasX-e.pos[0];(i<40||i>n-40)&&i>-3&&i<n+3||this.setValue(this.value+(o.deltaX??0)*Ke(this.options),{e:o,node:e,canvas:t})}},Nw=class extends B{static{h(this,"SelectButtonWidget")}type="selectbutton";drawWidget(o,e){const{width:t}=e,{y:n,height:i}=this,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d}=o;o.fillStyle=this.background_color,o.fillRect(15,n,t-30,i),o.strokeStyle=this.outline_color,o.strokeRect(15,n,t-30,i),o.fillStyle=this.text_color,o.font="11px monospace",o.textAlign="center",o.textBaseline="middle";const u=`SelectButton: ${ye("widgets.node2only")}`;o.fillText(u,t/2,n+i/2),Object.assign(o,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d})}onClick(o){}},xw=class extends B{static{h(this,"SliderWidget")}type="slider";marker;drawWidget(o,{width:e,showText:t=!0}){const{fillStyle:n,strokeStyle:i,textAlign:s}=o,{height:a,y:r}=this,{margin:l}=B;o.fillStyle=this.background_color,o.fillRect(l,r,e-l*2,a);const d=this.options.max-this.options.min;let u=(this.value-this.options.min)/d;if(u=pe(u,0,1),o.fillStyle=this.options.slider_color??"#678",o.fillRect(l,r,u*(e-l*2),a),t&&!this.computedDisabled&&(o.strokeStyle=this.outline_color,o.strokeRect(l,r,e-l*2,a)),this.marker!=null){let p=(this.marker-this.options.min)/d;p=pe(p,0,1),o.fillStyle=this.options.marker_color??"#AA9",o.fillRect(l+p*(e-l*2),r,2,a)}if(t){o.textAlign="center",o.fillStyle=this.text_color;const p=Number(this.value).toFixed(this.options.precision??3);o.fillText(`${this.label||this.name} ${p}`,e*.5,r+a*.7)}Object.assign(o,{textAlign:s,strokeStyle:i,fillStyle:n})}onClick(o){if(this.options.read_only)return;const{e,node:t}=o,n=this.width||t.size[0],i=pe((e.canvasX-t.pos[0]-15)/(n-30),0,1),s=this.options.min+(this.options.max-this.options.min)*i;s!==this.value&&this.setValue(s,o)}onDrag(o){if(this.options.read_only)return!1;const{e,node:t}=o,n=this.width||t.size[0],i=pe((e.canvasX-t.pos[0]-15)/(n-30),0,1),s=this.options.min+(this.options.max-this.options.min)*i;s!==this.value&&this.setValue(s,o)}},xo=class extends B{static{h(this,"TextWidget")}constructor(o,e){super(o,e),this.type??="string",this.value=o.value?.toString()??""}drawWidget(o,{width:e,showText:t=!0}){const{fillStyle:n,strokeStyle:i,textAlign:s}=o;this.drawWidgetShape(o,{width:e,showText:t}),t&&this.drawTruncatingText({ctx:o,width:e,leftPadding:0,rightPadding:0}),Object.assign(o,{textAlign:s,strokeStyle:i,fillStyle:n})}onClick({e:o,node:e,canvas:t}){t.prompt("Value",this.value,n=>{n!==null&&this.setValue(n,{e:o,node:e,canvas:t})},o,this.options?.multiline??!1)}},Aw=class extends B{static{h(this,"TextareaWidget")}type="textarea";drawWidget(o,e){this.drawVueOnlyWarning(o,e,"Textarea")}onClick(o){}},Dw=class extends B{static{h(this,"TreeSelectWidget")}type="treeselect";drawWidget(o,e){this.drawVueOnlyWarning(o,e,"TreeSelect")}onClick(o){}};function Ct(o,e,t=!0){if(o instanceof B)return o;const n=o;switch(n.type){case"button":return U(fw,n,e);case"toggle":return U(hw,n,e);case"slider":return U(xw,n,e);case"knob":return U(Iw,n,e);case"combo":return U(bw,n,e);case"number":return U(Ew,n,e);case"string":return U(xo,n,e);case"text":return U(xo,n,e);case"fileupload":return U(vw,n,e);case"color":return U(yw,n,e);case"markdown":return U(Tw,n,e);case"treeselect":return U(Dw,n,e);case"multiselect":return U(Lw,n,e);case"chart":return U(_w,n,e);case"galleria":return U(kw,n,e);case"imagecompare":return U(ww,n,e);case"selectbutton":return U(Nw,n,e);case"textarea":return U(Aw,n,e);case"asset":return U(En,n,e);case"imagecrop":return U(Sw,n,e);case"boundingbox":return U(gw,n,e);default:if(t)return U(Cw,o,e)}}h(Ct,"toConcreteWidget");function eI(o){return o.type==="combo"}h(eI,"isComboWidget");function tI(o){return o.type==="asset"}h(tI,"isAssetWidget");var q=class Qe{static{h(this,"LGraphNode")}static title;static MAX_CONSOLE;static type;static category;static description;static filter;static skip_list;static resizeHandleSize=15;static resizeEdgeSize=5;static keepAllLinksOnBypass=!1;title;get titleFontStyle(){return`${_.NODE_TEXT_SIZE}px ${_.NODE_FONT}`}get innerFontStyle(){return`normal ${_.NODE_SUBTEXT_SIZE}px ${_.NODE_FONT}`}get displayType(){return this.type}graph=null;id;type="";inputs=[];outputs=[];#e=[];#t=[];properties={};properties_info=[];flags={};widgets;changeTracker;freeWidgetSpace;locked;order=0;mode=H.ALWAYS;last_serialization;serialize_widgets;color;bgcolor;boxcolor;get renderingColor(){return uo(this.color||this.constructor.color||_.NODE_DEFAULT_COLOR,{lightness:_.nodeLightness})}get renderingBgColor(){const e=this.bgcolor||this.constructor.bgcolor||_.NODE_DEFAULT_BGCOLOR,t={opacity:_.nodeOpacity,lightness:_.nodeLightness};return uo(this.mode===H.BYPASS?_.NODE_DEFAULT_BYPASS_COLOR:e,t)}get renderingBoxColor(){if(this.boxcolor)return this.boxcolor;if(_.node_box_coloured_when_on){if(this.action_triggered)return"#FFF";if(this.execute_triggered)return"#AAA"}if(_.node_box_coloured_by_mode){const e=_.NODE_MODES_COLORS[this.mode??H.ALWAYS];if(e)return e}return _.NODE_DEFAULT_BOXCOLOR}setColorOption(e){e==null?(this.color=void 0,this.bgcolor=void 0):(this.color=e.color,this.bgcolor=e.bgcolor)}getColorOption(){return Object.values(ce.node_colors).find(e=>e.color===this.color&&e.bgcolor===this.bgcolor)??null}strokeStyles;progress;exec_version;action_call;execute_triggered;action_triggered;widgets_up;widgets_start_y;lostFocusAt;gotFocusAt;badges=[];title_buttons=[];badgePosition=So.TopLeft;_collapsed_width;console;_level;_shape;mouseOver;redraw_on_mouse;resizable;clonable;_relative_id;clip_area;ignore_remove;has_errors;removable;block_delete;selected;showAdvanced;isSubgraphNode(){return!1}#o=new X;get renderArea(){return this.#o}#n=new X;get boundingRect(){return this.#n}get boundingOffset(){const{pos:[e,t],boundingRect:[n,i]}=this;return[e-n,t-i]}_posSize=new X;_pos=this._posSize.pos;_size=this._posSize.size;get pos(){return this._pos}set pos(e){!e||e.length<2||(this._pos[0]=e[0],this._pos[1]=e[1])}get size(){return this._size}set size(e){!e||e.length<2||(this._size[0]=e[0],this._size[1]=e[1])}get renderingSize(){return this.flags.collapsed?[this._collapsed_width??0,0]:this._size}get shape(){return this._shape}set shape(e){const t=this._shape;switch(e){case"default":this._shape=void 0;break;case"box":this._shape=M.BOX;break;case"round":this._shape=M.ROUND;break;case"circle":this._shape=M.CIRCLE;break;case"card":this._shape=M.CARD;break;default:this._shape=e}t!==this._shape&&this.graph?.trigger("node:property:changed",{nodeId:this.id,property:"shape",oldValue:t,newValue:this._shape})}get renderingShape(){return this._shape||this.constructor.shape||_.NODE_DEFAULT_SHAPE}get is_selected(){return this.selected}set is_selected(e){this.selected=e}get title_mode(){return this.constructor.title_mode??se.NORMAL_TITLE}#s(){if(this.has_errors)return{padding:12,lineWidth:10,color:_.NODE_ERROR_COLOUR}}#i(){if(this.selected)return{padding:this.has_errors?20:void 0}}constructor(e,t){this.id=_.use_uuids?_.uuidv4():-1,this.title=e||"Unnamed",this.type=t??"",this.size=[_.NODE_WIDTH,60],this.pos=[10,10],this.strokeStyles={error:this.#s,selected:this.#i},this.changeTracker=new hs(this)}configure(e){this.graph&&this.graph._version++;for(const t in e){if(t=="properties"){for(const n in e.properties)this.properties[n]=e.properties[n],this.onPropertyChanged?.(n,e.properties[n]);continue}e[t]!=null&&(typeof e[t]=="object"?this[t]?.configure?this[t]?.configure(e[t]):this[t]=_.cloneObject(e[t],this[t]):this[t]=e[t])}e.title||(this.title=this.constructor.title),this.inputs??=[],this.inputs=this.inputs.map(t=>U(Be,t,this));for(const[t,n]of this.inputs.entries()){const i=this.graph&&n.link!=null?this.graph._links.get(n.link):null;this.onConnectionsChange?.(j.INPUT,t,!0,i,n),this.onInputAdded?.(n)}this.outputs??=[],this.outputs=this.outputs.map(t=>U(mt,t,this));for(const[t,n]of this.outputs.entries())if(n.links){for(const i of n.links){const s=this.graph?this.graph._links.get(i):null;this.onConnectionsChange?.(j.OUTPUT,t,!0,s,n)}this.onOutputAdded?.(n)}if(this._internalConfigureAfterSlots?.(),this.widgets){for(const t of this.widgets){if(!t)continue;const n=this.inputs.find(i=>i.widget?.name===t.name);n?.label&&(t.label=n.label),t.options?.property&&this.properties[t.options.property]!=null&&(t.value=JSON.parse(JSON.stringify(this.properties[t.options.property])))}if(e.widgets_values){let t=0;for(const n of this.widgets??[])if(n.serialize!==!1){if(t>=e.widgets_values.length)break;n.value=e.widgets_values[t++]}}}this.pinned&&(this.resizable=!1),this.onConfigure?.(e)}serialize(){const e={id:this.id,type:this.type,pos:[this.pos[0],this.pos[1]],size:[this.size[0],this.size[1]],flags:_.cloneObject(this.flags),order:this.order,mode:this.mode,showAdvanced:this.showAdvanced};if(this.constructor===Qe&&this.last_serialization)return{...this.last_serialization,mode:e.mode,pos:e.pos};this.inputs&&(e.inputs=this.inputs.map(n=>Zi(n))),this.outputs&&(e.outputs=this.outputs.map(n=>Ji(n))),this.title&&this.title!=this.constructor.title&&(e.title=this.title),this.properties&&(e.properties=_.cloneObject(this.properties));const{widgets:t}=this;if(t&&this.serialize_widgets){e.widgets_values=[];for(const[n,i]of t.entries())i.serialize!==!1&&(e.widgets_values[n]=i?i.value:null)}return!e.type&&this.constructor.type&&(e.type=this.constructor.type),this.color&&(e.color=this.color),this.bgcolor&&(e.bgcolor=this.bgcolor),this.boxcolor&&(e.boxcolor=this.boxcolor),this.shape&&(e.shape=this.shape),this.onSerialize?.(e)&&console.warn("node onSerialize shouldn't return anything, data should be stored in the object pass in the first parameter"),e}clone(){if(this.type==null)return null;const e=_.createNode(this.type);if(!e)return null;const t=_.cloneObject(this.serialize()),{inputs:n,outputs:i}=t;if(n)for(const s of n)s.link=null;if(i)for(const{links:s}of i)s&&(s.length=0);return t.id=void 0,_.use_uuids&&(t.id=_.uuidv4()),e.configure(t),e}toString(){return JSON.stringify(this.serialize())}getTitle(){return this.title||this.constructor.title}setProperty(e,t){if(this.properties||={},t===this.properties[e])return;const n=this.properties[e];if(this.properties[e]=t,this.onPropertyChanged?.(e,t,n)===!1&&(this.properties[e]=n),this.widgets){for(const i of this.widgets)if(i&&i.options.property==e){i.value=t;break}}}setOutputData(e,t){const{outputs:n}=this;if(!n||e==-1||e>=n.length)return;const i=n[e];if(!i)return;if(i._data=t,!this.graph)throw new N;const{links:s}=n[e];if(s)for(const a of s){const r=this.graph._links.get(a);r&&(r.data=t)}}setOutputDataType(e,t){const{outputs:n}=this;if(!n||e==-1||e>=n.length)return;const i=n[e];if(!i)return;if(i.type=t,!this.graph)throw new N;const{links:s}=n[e];if(s)for(const a of s){const r=this.graph._links.get(a);r&&(r.type=t)}}getInputData(e,t){if(!this.inputs||e>=this.inputs.length||this.inputs[e].link==null)return;if(!this.graph)throw new N;const n=this.inputs[e].link,i=this.graph._links.get(n);if(!i)return null;if(!t)return i.data;const s=this.graph.getNodeById(i.origin_id);return s&&(s.updateOutputData?s.updateOutputData(i.origin_slot):s.onExecute?.()),i.data}getInputDataType(e){if(!this.inputs||e>=this.inputs.length||this.inputs[e].link==null)return null;if(!this.graph)throw new N;const t=this.inputs[e].link,n=this.graph._links.get(t);if(!n)return null;const i=this.graph.getNodeById(n.origin_id);if(!i)return n.type;const s=i.outputs[n.origin_slot];return s?s.type:null}getInputDataByName(e,t){const n=this.findInputSlot(e);return n==-1?null:this.getInputData(n,t)}isInputConnected(e){return this.inputs?e<this.inputs.length&&this.inputs[e].link!=null:!1}getInputInfo(e){return!this.inputs||!(e<this.inputs.length)?null:this.inputs[e]}getInputLink(e){if(!this.inputs)return null;if(e<this.inputs.length){if(!this.graph)throw new N;const t=this.inputs[e];if(t.link!=null)return this.graph._links.get(t.link)??null}return null}getInputNode(e){if(!this.inputs||e>=this.inputs.length)return null;const t=this.inputs[e];if(!t||t.link===null)return null;if(!this.graph)throw new N;const n=this.graph._links.get(t.link);return n?this.graph.getNodeById(n.origin_id):null}getInputOrProperty(e){const{inputs:t}=this;if(!t?.length)return this.properties?this.properties[e]:null;if(!this.graph)throw new N;for(const n of t)if(e==n.name&&n.link!=null){const i=this.graph._links.get(n.link);if(i)return i.data}return this.properties[e]}getOutputData(e){return!this.outputs||e>=this.outputs.length?null:this.outputs[e]._data}getOutputInfo(e){return!this.outputs||!(e<this.outputs.length)?null:this.outputs[e]}isOutputConnected(e){return this.outputs?e<this.outputs.length&&Number(this.outputs[e].links?.length)>0:!1}isAnyOutputConnected(){const{outputs:e}=this;if(!e)return!1;for(const t of e)if(t.links?.length)return!0;return!1}getOutputNodes(e){const{outputs:t}=this;if(!t||t.length==0||e>=t.length)return null;const{links:n}=t[e];if(!n||n.length==0)return null;if(!this.graph)throw new N;const i=[];for(const s of n){const a=this.graph._links.get(s);if(a){const r=this.graph.getNodeById(a.target_id);r&&i.push(r)}}return i}addOnTriggerInput(){const e=this.findInputSlot("onTrigger");return e==-1?(this.addInput("onTrigger",_.EVENT,{nameLocked:!0}),this.findInputSlot("onTrigger")):e}addOnExecutedOutput(){const e=this.findOutputSlot("onExecuted");return e==-1?(this.addOutput("onExecuted",_.ACTION,{nameLocked:!0}),this.findOutputSlot("onExecuted")):e}onAfterExecuteNode(e,t){const n=this.findOutputSlot("onExecuted");n!=-1&&this.triggerSlot(n,e,null,t)}changeMode(e){switch(e){case H.ON_EVENT:break;case H.ON_TRIGGER:this.addOnTriggerInput(),this.addOnExecutedOutput();break;case H.NEVER:break;case H.ALWAYS:break;case _.ON_REQUEST:break;default:return!1}return this.mode=e,!0}doExecute(e,t){if(t=t||{},this.onExecute){if(t.action_call||=`${this.id}_exec_${Math.floor(Math.random()*9999)}`,!this.graph)throw new N;this.graph.nodes_executing[this.id]=!0,this.onExecute(e,t),this.graph.nodes_executing[this.id]=!1,this.exec_version=this.graph.iteration,t?.action_call&&(this.action_call=t.action_call,this.graph.nodes_executedAction[this.id]=t.action_call)}this.execute_triggered=2,this.onAfterExecuteNode?.(e,t)}actionDo(e,t,n){if(n=n||{},this.onAction){if(n.action_call||=`${this.id}_${e||"action"}_${Math.floor(Math.random()*9999)}`,!this.graph)throw new N;this.graph.nodes_actioning[this.id]=e||"actioning",this.onAction(e,t,n),this.graph.nodes_actioning[this.id]=!1,n?.action_call&&(this.action_call=n.action_call,this.graph.nodes_executedAction[this.id]=n.action_call)}this.action_triggered=2,this.onAfterExecuteNode?.(t,n)}trigger(e,t,n){const{outputs:i}=this;if(!(!i||!i.length)){this.graph&&(this.graph._last_trigger_time=_.getTime());for(const[s,a]of i.entries())!a||a.type!==_.EVENT||e&&a.name!=e||this.triggerSlot(s,t,null,n)}}triggerSlot(e,t,n,i){if(i=i||{},!this.outputs)return;if(e==null){console.error("slot must be a number");return}typeof e!="number"&&console.warn("slot must be a number, use node.trigger('name') if you want to use a string");const s=this.outputs[e];if(!s)return;const a=s.links;if(!(!a||!a.length)){if(!this.graph)throw new N;this.graph._last_trigger_time=_.getTime();for(const r of a){if(n!=null&&n!=r)continue;const l=this.graph._links.get(r);if(!l)continue;l._last_time=_.getTime();const d=this.graph.getNodeById(l.target_id);if(d){if(d.mode===H.ON_TRIGGER)i.action_call||(i.action_call=`${this.id}_trigg_${Math.floor(Math.random()*9999)}`),d.doExecute?.(t,i);else if(d.onAction){i.action_call||(i.action_call=`${this.id}_act_${Math.floor(Math.random()*9999)}`);const u=d.inputs[l.target_slot];d.actionDo(u.name,t,i)}}}}}clearTriggeredSlot(e,t){if(!this.outputs)return;const n=this.outputs[e];if(!n)return;const i=n.links;if(!(!i||!i.length)){if(!this.graph)throw new N;for(const s of i){if(t!=null&&t!=s)continue;const a=this.graph._links.get(s);a&&(a._last_time=0)}}}setSize(e){this.size=e,this.onResize?.(this.size)}expandToFitContent(){const e=this.computeSize();this.setSize([Math.max(this.size[0],e[0]),Math.max(this.size[1],e[1])])}addProperty(e,t,n,i){const s={name:e,type:n,default_value:t};return i&&Object.assign(s,i),this.properties_info||=[],this.properties_info.push(s),this.properties||={},this.properties[e]=t,s}addOutput(e,t,n){const i=Object.assign(new mt({name:e,type:t,links:null},this),n);return this.outputs||=[],this.outputs.push(i),this.onOutputAdded?.(i),_.auto_load_slot_types&&_.registerNodeAndSlotType(this,t,!0),this.expandToFitContent(),this.setDirtyCanvas(!0,!0),i}removeOutput(e){this.graph&&this.disconnectOutput(e);const{outputs:t}=this;t.splice(e,1);for(let n=e;n<t.length;++n){const i=t[n];if(!(!i||!i.links)&&this.graph)for(const s of i.links){const a=this.graph._links.get(s);a&&a.origin_slot--}}this.onOutputRemoved?.(e),this.setDirtyCanvas(!0,!0)}addInput(e,t,n){t||=0;const i=Object.assign(new Be({name:e,type:t,link:null},this),n);return this.inputs||=[],this.inputs.push(i),this.expandToFitContent(),this.onInputAdded?.(i),_.registerNodeAndSlotType(this,t),this.setDirtyCanvas(!0,!0),i}removeInput(e){this.graph&&this.disconnectInput(e,!0);const{inputs:t}=this,n=t.splice(e,1);for(let i=e;i<t.length;++i){const s=t[i];if(s?.link&&this.graph){const a=this.graph._links.get(s.link);a&&a.target_slot--}}this.onInputRemoved?.(e,n[0]),this.setDirtyCanvas(!0,!0)}computeSize(e){const t=this.constructor.size;if(t)return[t[0],t[1]];const{inputs:n,outputs:i,widgets:s}=this;let a=Math.max(n?n.filter(C=>!we(C)).length:1,i?i.length:1);const r=e??[0,0];a=Math.max(a,1);const l=_.NODE_TEXT_SIZE,d=_.NODE_TITLE_HEIGHT,u=d*.33,p=d+E(this.title,this.titleFontStyle)+u;let m=0,g=0,f=0;if(n)for(const C of n){const I=E(C.label||C.localized_name||C.name||"",this.innerFontStyle);if(we(C)){const P=this.getWidgetFromSlot(C);if(P&&!this.isWidgetVisible(P))continue;I>g&&(g=I)}else I>m&&(m=I)}if(i)for(const C of i){const I=E(C.label||C.localized_name||C.name||"",this.innerFontStyle);f<I&&(f=I)}const y=_.NODE_WIDTH*(s?.length?1.5:1),b=m&&f?5:0,v=m+f+2*_.NODE_SLOT_HEIGHT+b,k=B.margin+B.arrowMargin+B.arrowWidth,w=B.minValueWidth+2*k;g&&(g+=w),r[0]=Math.max(v,g,p,y),r[1]=(this.constructor.slot_start_y||0)+a*_.NODE_SLOT_HEIGHT;let S=0;if(s?.length){for(const C of s){if(!this.isWidgetVisible(C))continue;let I=0;if(C.computeSize)I+=C.computeSize(r[0])[1];else if(C.computeLayoutSize){const{minHeight:P,minWidth:A}=C.computeLayoutSize(this),F=A+w;F>r[0]&&(r[0]=F),I+=P}else I+=_.NODE_WIDGET_HEIGHT;S+=I+4}S+=8}this.widgets_up?r[1]=Math.max(r[1],S):this.widgets_start_y!=null?r[1]=Math.max(r[1],S+this.widgets_start_y):r[1]+=S;function E(C,I){return ce._measureText?.(C,I)??l*(C?.length??0)*.6}return h(E,"compute_text_size"),this.constructor.min_height&&r[1]<this.constructor.min_height&&(r[1]=this.constructor.min_height),r[1]+=6,r}inResizeCorner(e,t){const n=this.outputs?this.outputs.length:1,i=(this.constructor.slot_start_y||0)+n*_.NODE_SLOT_HEIGHT;return G(e,t,this.pos[0]+this.size[0]-15,this.pos[1]+Math.max(this.size[1]-15,i),20,20)}findResizeDirection(e,t){if(this.resizable===!1)return;const{boundingRect:n}=this;if(n.containsXy(e,t))return n.findContainingCorner(e,t,Qe.resizeHandleSize)}getPropertyInfo(e){let t=null;const{properties_info:n}=this;if(n){for(const i of n)if(i.name==e){t=i;break}}return this.constructor[`@${e}`]&&(t=this.constructor[`@${e}`]),this.constructor.widgets_info?.[e]&&(t=this.constructor.widgets_info[e]),!t&&this.onGetPropertyInfo&&(t=this.onGetPropertyInfo(e)),t||={},t.type||=typeof this.properties[e],t.widget=="combo"&&(t.type="enum"),t}addWidget(e,t,n,i,s){this.widgets||=[],!s&&i&&typeof i=="object"&&(s=i,i=null),s||={},typeof s=="string"&&(s={property:s}),i&&typeof i=="string"&&(s.property=i,i=null);const a={type:e.toLowerCase(),name:t,value:n,callback:typeof i!="function"?void 0:i,options:s,y:0};if(a.options.y!==void 0&&(a.y=a.options.y),!i&&!a.options.callback&&!a.options.property&&console.warn("LiteGraph addWidget(...) without a callback or property assigned"),e=="combo"&&!a.options.values)throw"LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }";const r=this.addCustomWidget(a);return this.expandToFitContent(),r}addCustomWidget(e){this.widgets||=[];const t=Ct(e,this,!1)??e;return this.widgets.push(t),t}addTitleButton(e){this.title_buttons||=[];const t=new bs(e);return this.title_buttons.push(t),t}onTitleButtonClick(e,t){t.dispatch("litegraph:node-title-button-clicked",{node:this,button:e})}removeWidgetByName(e){const t=this.widgets?.find(n=>n.name===e);t&&this.removeWidget(t)}removeWidget(e){if(!this.widgets)throw new Error("removeWidget called on node without widgets");const t=this.widgets.indexOf(e);if(t===-1)throw new Error("Widget not found on this node");if(this.inputs)for(const n of this.inputs)n._widget===e&&(n._widget=void 0,n.widget=void 0);e.onRemove?.(),this.widgets.splice(t,1)}ensureWidgetRemoved(e){try{this.removeWidget(e)}catch(t){console.error("Failed to remove widget",t)}}move(e,t){this.pinned||_.vueNodesMode||(this.pos[0]+=e,this.pos[1]+=t)}measure(e,t){const n=this.title_mode,i=n!=se.TRANSPARENT_TITLE&&n!=se.NO_TITLE?_.NODE_TITLE_HEIGHT:0;e[0]=this.pos[0],e[1]=this.pos[1]+-i,this.flags?.collapsed?(t&&(t.font=this.innerFontStyle),this._collapsed_width=Math.min(this.size[0],t?t.measureText(this.getTitle()??"").width+_.NODE_TITLE_HEIGHT*2:0),e[2]=this._collapsed_width||_.NODE_COLLAPSED_WIDTH,e[3]=_.NODE_TITLE_HEIGHT):(e[2]=this.size[0],e[3]=this.size[1]+i)}getBounding(e,t){e||=[0,0,0,0];const n=t?this.renderArea:this.boundingRect;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e}updateArea(e){const t=this.#n;this.measure(t,e),this.onBounding?.(t);const n=this.#o;n.set(t),n[0]-=4,n[1]-=4,n[2]+=10,n[3]+=9}isPointInside(e,t){return yt(e,t,this.boundingRect)}isPointInCollapse(e,t){const n=_.NODE_TITLE_HEIGHT;return G(e,t,this.pos[0],this.pos[1]-n,n,n)}getInputOnPos(e){return mn(this,e[0],e[1])?.input}getOutputOnPos(e){return hn(this,e[0],e[1])?.output}getSlotOnPos(e){if(We(e,this.boundingRect))return this.getInputOnPos(e)??this.getOutputOnPos(e)}getSlotInPosition(e,t){const{inputs:n,outputs:i}=this;if(n)for(const[s,a]of n.entries()){const r=this.getInputPos(s);if(G(e,t,r[0]-10,r[1]-10,20,20))return{input:a,slot:s,link_pos:r}}if(i)for(const[s,a]of i.entries()){const r=this.getOutputPos(s);if(G(e,t,r[0]-10,r[1]-10,20,20))return{output:a,slot:s,link_pos:r}}return null}getWidgetOnPos(e,t,n=!1){const{widgets:i,pos:s,size:a}=this;if(!i?.length)return;const r=e-s[0],l=t-s[1],d=a[0];for(const u of i){if(u.computedDisabled&&!n||!this.isWidgetVisible(u))continue;const p=u.computedHeight??u.computeSize?.(d)[1]??_.NODE_WIDGET_HEIGHT,m=u,g=m.margin??-2,f=m.margin??2,y=m.margin??6,b=u.width||d;if(u.last_y!==void 0&&G(r,l,y,u.last_y+g,b-2*y,p-g-f))return u}}findInputSlot(e,t=!1){const{inputs:n}=this;if(!n)return-1;for(const[i,s]of n.entries())if(e==s.name)return t?s:i;return-1}findOutputSlot(e,t=!1){const{outputs:n}=this;if(!n)return-1;for(const[i,s]of n.entries())if(e==s.name)return t?s:i;return-1}findInputSlotFree(e){return this.#d(this.inputs,e)}findOutputSlotFree(e){return this.#d(this.outputs,e)}#d(e,t){const n=Object.assign({returnObj:!1,typesNotAccepted:[]},t||{}),i=e?.length;if(!(i>0))return-1;for(let s=0;s<i;++s){const a=e[s];if(!(!a||a.link||a.links?.length)&&!n.typesNotAccepted?.includes?.(a.type))return n.returnObj?a:s}return-1}findInputSlotByType(e,t,n,i){return this.#a(this.inputs,e,t,n,i)}findOutputSlotByType(e,t,n,i){return this.#a(this.outputs,e,t,n,i)}findSlotByType(e,t,n,i,s){return e?this.#a(this.inputs,t,n,i,s):this.#a(this.outputs,t,n,i,s)}#a(e,t,n,i,s){const a=e?.length;if(!a)return-1;(t==""||t=="*")&&(t=0);const r=String(t).toLowerCase().split(",");let l=null;for(let d=0;d<a;++d){const u=e[d],p=u.type=="0"||u.type=="*"?["0"]:String(u.type).toLowerCase().split(",");for(const m of r){const g=m=="_event_"?_.EVENT:m;for(const f of p){const y=f=="_event_"?_.EVENT:f;if(g==y||g==="*"||y==="*"){if(i&&(u.links?.length||u.link!=null)){l??=n?u:d;continue}return n?u:d}}}}return s?-1:l??-1}findConnectByTypeSlot(e,t,n,i){i&&typeof i=="object"&&("firstFreeIfInputGeneralInCase"in i&&(i.wildcardToTyped=!!i.firstFreeIfInputGeneralInCase),"firstFreeIfOutputGeneralInCase"in i&&(i.wildcardToTyped=!!i.firstFreeIfOutputGeneralInCase),"generalTypeInCase"in i&&(i.typedToWildcard=!!i.generalTypeInCase));const s=Object.assign({createEventInCase:!0,wildcardToTyped:!0,typedToWildcard:!0},i);if(!this.graph)throw new N;if(t&&typeof t=="number"){const r=this.graph.getNodeById(t);if(!r)return;t=r}const a=t.findSlotByType(e,n,!1,!0);if(a>=0&&a!==null)return a;if(s.createEventInCase&&n==_.EVENT){if(e)return-1;if(_.do_add_triggers_slots)return t.addOnExecutedOutput()}if(s.typedToWildcard){const r=t.findSlotByType(e,0,!1,!0,!0);if(r>=0)return r}if(s.wildcardToTyped&&(n==0||n=="*"||n=="")){const r={typesNotAccepted:[_.EVENT]},l=e?t.findInputSlotFree(r):t.findOutputSlotFree(r);if(l>=0)return l}}findOutputByType(e){return vt(this.outputs,e,t=>!t.links?.length)}findInputByType(e){return vt(this.inputs,e,t=>t.link==null||!!this.graph?.getLink(t.link)?._dragging)}connectByType(e,t,n,i){const s=this.findConnectByTypeSlot(!0,t,n,i);return s!==void 0?this.connect(e,t,s,i?.afterRerouteId):null}connectByTypeOutput(e,t,n,i){typeof i=="object"&&("firstFreeIfInputGeneralInCase"in i&&(i.wildcardToTyped=!!i.firstFreeIfInputGeneralInCase),"generalTypeInCase"in i&&(i.typedToWildcard=!!i.generalTypeInCase));const s=this.findConnectByTypeSlot(!1,t,n,i);return s!==void 0?t.connect(s,this,e,i?.afterRerouteId):(console.error("[connectByType]: no way to connect type:",n,"to node:",t),null)}canConnectTo(e,t,n){return this.id!==e.id&&_.isValidConnection(n.type,t.type)}connect(e,t,n,i){let s;const{graph:a,outputs:r}=this;if(!a)return console.error("Connect: Error, node doesn't belong to any graph. Nodes must be added first to a graph before connecting them."),null;if(typeof e=="string"){if(e=this.findOutputSlot(e),e==-1)return _.debug&&console.error(`Connect: Error, no slot of name ${e}`),null}else if(!r||e>=r.length)return _.debug&&console.error("Connect: Error, slot number not found"),null;if(t&&typeof t=="number"){const u=a.getNodeById(t);if(!u)throw"target node is null";t=u}if(!t)throw"target node is null";if(t==this)return null;if(typeof n=="string"){if(s=t.findInputSlot(n),s==-1)return _.debug&&console.error(`Connect: Error, no slot of name ${s}`),null}else if(n===_.EVENT)if(_.do_add_triggers_slots)t.changeMode(H.ON_TRIGGER),s=t.findInputSlot("onTrigger");else return null;else typeof n=="number"?s=n:s=0;if(t.onBeforeConnectInput){const u=t.onBeforeConnectInput(s,n);s=typeof u=="number"?u:null}if(s===null||!t.inputs||s>=t.inputs.length)return _.debug&&console.error("Connect: Error, slot number not found"),null;const l=t.inputs[s],d=r[e];return d?(d.links?.length&&d.type===_.EVENT&&!_.allow_multi_output_for_events&&(a.beforeChange(),this.disconnectOutput(e)),this.connectSlots(d,t,l,i)??null):null}connectSlots(e,t,n,i){const{graph:s}=this;if(!s)throw new N;const a=Ae(),r=this.outputs.indexOf(e);if(r===-1){console.warn("connectSlots: output not found");return}const l=t.inputs.indexOf(n);if(l===-1){console.warn("connectSlots: input not found");return}if(!_.isValidConnection(e.type,n.type))return this.setDirtyCanvas(!1,!0),null;if(t.onConnectInput?.(l,e.type,e,this,r)===!1||this.onConnectOutput?.(r,n.type,n,t,l)===!1)return null;t.inputs[l]?.link!=null&&(s.beforeChange(),t.disconnectInput(l,!0));const d=n.type&&e.type&&gs(n.type,e.type),u=new z(++s.state.lastLinkId,d||n.type||e.type,this.id,r,t.id,l,i);s._links.set(u.id,u),a.setSource(ue.Canvas),a.createLink(u.id,this.id,r,t.id,l),e.links??=[],e.links.push(u.id);const p=t.inputs[l];p.link=u.id,p.widget&&s.trigger("node:slot-links:changed",{nodeId:t.id,slotType:j.INPUT,slotIndex:l,connected:!0,linkId:u.id});const m=z.getReroutes(s,u);for(const f of m)f.linkIds.add(u.id),f.floating&&(f.floating=void 0),f._dragging=void 0;const g=m.at(-1);if(g)for(const f of g.floatingLinkIds){const y=s.floatingLinks.get(f);y?.parentId===g.id&&s.removeFloatingLink(y)}return s._version++,this.onConnectionsChange?.(j.OUTPUT,r,!0,u,e),t.onConnectionsChange?.(j.INPUT,l,!0,u,n),this.setDirtyCanvas(!1,!0),s.afterChange(),u}connectFloatingReroute(e,t,n){const{graph:i,id:s}=this;if(!i)throw new N;const a=this.inputs.indexOf(t),r=this.outputs.indexOf(t);if(a===-1&&r===-1)throw new Error("Invalid slot");const l=r===-1?"input":"output",d=i.setReroute({pos:e,parentId:n,linkIds:[],floating:{slotType:l}}),u=i.getReroute(n),p=u?.floating?.slotType==="output";if(n==null||!p){const g=new z(-1,t.type,r===-1?-1:s,r,a===-1?-1:s,a);return g.parentId=d.id,i.addFloatingLink(g),d}if(!u)throw new Error("[connectFloatingReroute] Parent reroute not found");const m=u.getFloatingLinks("output")?.[0];if(!m)throw new Error("[connectFloatingReroute] Floating link not found");return d.floatingLinkIds.add(m.id),m.parentId=d.id,u.floating=void 0,d}disconnectOutput(e,t){if(typeof e=="string"){if(e=this.findOutputSlot(e),e==-1)return _.debug&&console.error(`Connect: Error, no slot of name ${e}`),!1}else if(!this.outputs||e>=this.outputs.length)return _.debug&&console.error("Connect: Error, slot number not found"),!1;const n=this.outputs[e];if(!n)return!1;if(n._floatingLinks)for(const a of n._floatingLinks)a.hasOrigin(this.id,e)&&this.graph?.removeFloatingLink(a);if(!n.links||n.links.length==0)return!1;const{links:i}=n,s=this.graph;if(!s)throw new N;if(t){const a=typeof t=="number"?s.getNodeById(t):t;if(!a)throw"Target Node not found";for(const[r,l]of i.entries()){const d=s._links.get(l);if(d?.target_id!=a.id)continue;i.splice(r,1);const u=a.inputs[d.target_slot];u.link=null,u.widget&&s.trigger("node:slot-links:changed",{nodeId:a.id,slotType:j.INPUT,slotIndex:d.target_slot,connected:!1,linkId:d.id}),d.disconnect(s,"input"),s._version++,a.onConnectionsChange?.(j.INPUT,d.target_slot,!1,d,u),this.onConnectionsChange?.(j.OUTPUT,e,!1,d,n);break}}else{for(const a of i){const r=s._links.get(a);if(!r)continue;if(r.target_id===-20&&s instanceof De){const d=s.outputNode.slots[r.target_slot];d?d.linkIds.length=0:console.error("Missing subgraphOutput slot when disconnecting link")}const l=s.getNodeById(r.target_id);if(s._version++,l){const d=l.inputs[r.target_slot];d.link=null,d.widget&&s.trigger("node:slot-links:changed",{nodeId:l.id,slotType:j.INPUT,slotIndex:r.target_slot,connected:!1,linkId:r.id}),l.onConnectionsChange?.(j.INPUT,r.target_slot,!1,r,d)}r.disconnect(s,"input"),this.onConnectionsChange?.(j.OUTPUT,e,!1,r,n)}n.links=null}return this.setDirtyCanvas(!1,!0),!0}disconnectInput(e,t){if(typeof e=="string"){if(e=this.findInputSlot(e),e==-1)return _.debug&&console.error(`Connect: Error, no slot of name ${e}`),!1}else if(!this.inputs||e>=this.inputs.length)return _.debug&&console.error("Connect: Error, slot number not found"),!1;const n=this.inputs[e];if(!n)return console.error("disconnectInput: input not found",e,this.inputs),!1;const{graph:i}=this;if(!i)throw new N;if(n._floatingLinks?.size)for(const a of n._floatingLinks)i.removeFloatingLink(a);const s=this.inputs[e].link;if(s!=null){this.inputs[e].link=null,n.widget&&i.trigger("node:slot-links:changed",{nodeId:this.id,slotType:j.INPUT,slotIndex:e,connected:!1,linkId:s});const a=i._links.get(s);if(a){if(a.origin_id===-10&&"inputNode"in i)return i.inputNode._disconnectNodeInput(this,n,a),!0;const r=i.getNodeById(a.origin_id);if(!r)return console.error("disconnectInput: output not found",a.origin_slot),!1;const l=r.outputs[a.origin_slot];if(!l?.links?.length)return!1;let d=0;for(const u=l.links.length;d<u;d++)if(l.links[d]==s){l.links.splice(d,1);break}a.disconnect(i,t?"output":void 0),i&&i._version++,this.onConnectionsChange?.(j.INPUT,e,!1,a,n),r.onConnectionsChange?.(j.OUTPUT,d,!1,a,l)}}return this.setDirtyCanvas(!1,!0),!0}getConnectionPos(e,t,n){n||=[0,0];const{pos:[i,s],inputs:a,outputs:r}=this;if(this.flags.collapsed){const m=this._collapsed_width||_.NODE_COLLAPSED_WIDTH;return n[0]=e?i:i+m,n[1]=s-_.NODE_TITLE_HEIGHT*.5,n}if(e&&t==-1)return n[0]=i+_.NODE_TITLE_HEIGHT*.5,n[1]=s+_.NODE_TITLE_HEIGHT*.5,n;const l=a?.[t]?.pos,d=r?.[t]?.pos;if(e&&l)return n[0]=i+l[0],n[1]=s+l[1],n;if(!e&&d)return n[0]=i+d[0],n[1]=s+d[1],n;const u=_.NODE_SLOT_HEIGHT*.5,p=e?this.#c.indexOf(this.inputs[t]):this.#r.indexOf(this.outputs[t]);return n[0]=e?i+u:i+this.size[0]+1-u,n[1]=s+(p+.7)*_.NODE_SLOT_HEIGHT+(this.constructor.slot_start_y||0),n}get#c(){return this.inputs.filter(e=>!e.pos&&!(this.widgets?.length&&we(e)))}get#r(){return this.outputs.filter(e=>!e.pos)}#l(){return{nodeX:this.pos[0],nodeY:this.pos[1],nodeWidth:this.size[0],nodeHeight:this.size[1],collapsed:this.flags.collapsed??!1,collapsedWidth:this._collapsed_width,slotStartY:this.constructor.slot_start_y,inputs:this.inputs,outputs:this.outputs,widgets:this.widgets}}getInputPos(e){return ae(this,e,!0)}getInputSlotPos(e){return rn(this.#l(),e)}getOutputPos(e){return ae(this,e,!1)}getSlotPosition(e,t){return ae(this,e,t)}snapToGrid(e){return this.pinned?!1:xe(this.pos,e)}alignToGrid(){this.snapToGrid(_.CANVAS_GRID_SIZE)}trace(e){this.console||=[],this.console.push(e),this.console.length>Qe.MAX_CONSOLE&&this.console.shift()}setDirtyCanvas(e,t){this.graph?.canvasAction(n=>n.setDirty(e,t))}loadImage(e){const t=new Image;t.src=_.node_images_path+e,t.ready=!1;const n=h(()=>this.setDirtyCanvas(!0),"dirty");return t.addEventListener("load",function(){this.ready=!0,n()}),t}captureInput(e){if(Tn("[DEPRECATED] captureInput will be removed in a future version. Please use LGraphCanvas.pointer (CanvasPointer) instead."),!this.graph||!this.graph.list_of_graphcanvas)return;const t=this.graph.list_of_graphcanvas;for(const n of t)!e&&n.node_capturing_input!=this||(n.node_capturing_input=e?this:null)}get collapsed(){return!!this.flags.collapsed}get collapsible(){return!this.pinned&&this.constructor.collapsable!==!1}collapse(e){if(!(!this.collapsible&&!e)){if(!this.graph)throw new N;this.graph._version++,this.flags.collapsed=!this.flags.collapsed,this.setDirtyCanvas(!0,!0)}}toggleAdvanced(){if(this.widgets?.some(e=>e.advanced)){if(!this.graph)throw new N;this.graph._version++,this.showAdvanced=!this.showAdvanced,this.expandToFitContent(),this.setDirtyCanvas(!0,!0)}}get pinned(){return!!this.flags.pinned}pin(e){if(!this.graph)throw new N;this.graph._version++,this.flags.pinned=e??!this.flags.pinned,this.resizable=!this.pinned,this.pinned||(this.flags.pinned=void 0)}unpin(){this.pin(!1)}localToScreen(e,t,n){return[(e+this.pos[0])*n.scale+n.offset[0],(t+this.pos[1])*n.scale+n.offset[1]]}get width(){return this.collapsed?this._collapsed_width||_.NODE_COLLAPSED_WIDTH:this.size[0]}get height(){return _.NODE_TITLE_HEIGHT+this.bodyHeight}get bodyHeight(){return this.collapsed?0:this.size[1]}drawBadges(e,{gap:t=2}={}){const n=this.badges.map(a=>a instanceof io?a:a());let i=this.badgePosition===So.TopLeft?0:this.width-n.reduce((a,r)=>a+r.getWidth(e)+t,0);const s=-(_.NODE_TITLE_HEIGHT+t);for(const a of n)a.draw(e,i,s-a.height),i+=a.getWidth(e)+t}drawTitleBarBackground(e,{scale:t,title_height:n=_.NODE_TITLE_HEIGHT,low_quality:i=!1}){const s=this.renderingColor,a=this.renderingShape,r=this.renderingSize;if(this.onDrawTitleBar){this.onDrawTitleBar(e,n,r,t,s);return}this.title_mode!==se.TRANSPARENT_TITLE&&(this.collapsed&&(e.shadowColor=_.DEFAULT_SHADOW_COLOR),e.fillStyle=this.constructor.title_color||s,e.beginPath(),a==M.BOX||i?e.rect(0,-n,r[0],n):(a==M.ROUND||a==M.CARD)&&e.roundRect(0,-n,r[0],n,this.collapsed?[_.ROUND_RADIUS]:[_.ROUND_RADIUS,_.ROUND_RADIUS,0,0]),e.fill(),e.shadowColor="transparent")}drawTitleBox(e,{scale:t,low_quality:n=!1,title_height:i=_.NODE_TITLE_HEIGHT,box_size:s=10}){const a=this.renderingSize,r=this.renderingShape;if(this.onDrawTitleBox){this.onDrawTitleBox(e,i,a,t);return}[M.ROUND,M.CIRCLE,M.CARD].includes(r)?(n&&(e.fillStyle="black",e.beginPath(),e.arc(i*.5,i*-.5,s*.5+1,0,Math.PI*2),e.fill()),e.fillStyle=this.renderingBoxColor,n?e.fillRect(i*.5-s*.5,i*-.5-s*.5,s,s):(e.beginPath(),e.arc(i*.5,i*-.5,s*.5,0,Math.PI*2),e.fill())):(n&&(e.fillStyle="black",e.fillRect((i-s)*.5-1,(i+s)*-.5-1,s+2,s+2)),e.fillStyle=this.renderingBoxColor,e.fillRect((i-s)*.5,(i+s)*-.5,s,s))}drawTitleText(e,{scale:t,default_title_color:n,low_quality:i=!1,title_height:s=_.NODE_TITLE_HEIGHT}){const a=this.renderingSize,r=this.selected;if(this.onDrawTitleText){this.onDrawTitleText(e,s,a,t,this.titleFontStyle,r);return}if(i)return;e.font=this.titleFontStyle;const l=this.getTitle()??`❌ ${this.type}`,d=String(l)+(this.pinned?"📌":"");if(d){r?e.fillStyle=_.NODE_SELECTED_TITLE_COLOR:e.fillStyle=this.constructor.title_text_color||n;let u=a[0]-s*2;if(this.title_buttons?.length>0){let m=0;const g=e.font;for(const f of this.title_buttons)f.visible&&(m+=f.getWidth(e)+2);e.font=g,m>0&&(m-=20,u-=m)}let p=d;this.collapsed?p=d.substr(0,20):u>0&&(p=Rs(e,d,u)),e.textAlign="left",e.fillText(p,s,_.NODE_TITLE_TEXT_Y-s)}}connectInputToOutput(){const{inputs:e,outputs:t,graph:n}=this;if(!e||!t)return;if(!n)throw new N;const{_links:i}=n;let s=!1;for(const[r,l]of e.entries()){if(l.link==null)continue;const d=t[r];if(!d||!_.isValidConnection(l.type,d.type))continue;const u=i.get(l.link);if(!u)continue;const p=n.getNodeById(u?.origin_id);p&&a(d,p,u,n)}if(!(this.flags.keepAllLinksOnBypass??Qe.keepAllLinksOnBypass))return s;for(const r of e){if(r.link==null)continue;const l=i.get(r.link);if(!l)continue;const d=n.getNodeById(l?.origin_id);if(d){for(const u of t)if(_.isValidConnection(r.type,u.type)){a(u,d,l,n);break}}}return s;function a(r,l,d,u){const p=r.links?.map(m=>i.get(m)).filter(m=>!!m);if(p?.length)for(const m of p){const g=u.getNodeById(m.target_id);if(!g)continue;const f=l.connect(d.origin_slot,g,m.target_slot,d.parentId);s||=!!f}}}isWidgetVisible(e){return!(this.collapsed||e.hidden||e.advanced&&!this.showAdvanced)}updateComputedDisabled(){if(this.widgets)for(const e of this.widgets)e.computedDisabled=e.disabled||this.getSlotFromWidget(e)?.link!=null}drawWidgets(e,{lowQuality:t=!1,editorAlpha:n=1}){if(!this.widgets)return;const i=this.size[0],{widgets:s}=this,a=_.NODE_WIDGET_HEIGHT,r=!t;e.save(),e.globalAlpha=n,this.updateComputedDisabled();for(const l of s){if(!this.isWidgetVisible(l))continue;const{y:d}=l,u=l.advanced?_.WIDGET_ADVANCED_OUTLINE_COLOR:_.WIDGET_OUTLINE_COLOR;l.last_y=d,e.strokeStyle=u,e.fillStyle="#222",e.textAlign="left",l.computedDisabled&&(e.globalAlpha*=.5);const p=l.width||i;typeof l.draw=="function"?l.draw(e,this,p,d,a,t):Ct(l,this,!1)?.drawWidget(e,{width:p,showText:r}),e.globalAlpha=n}e.restore()}drawCollapsedSlots(e){for(const t of this.#e)if(t.link!=null){t.drawCollapsed(e);break}for(const t of this.#t)if(t.links?.length){t.drawCollapsed(e);break}}get slots(){return[...this.inputs,...this.outputs]}#u(e,t,n){const i=n?this.getInputPos(t):this.getOutputPos(t);e.boundingRect[0]=i[0]-_.NODE_SLOT_HEIGHT*.5,e.boundingRect[1]=i[1]-_.NODE_SLOT_HEIGHT*.5,e.boundingRect[2]=e.isWidgetInputSlot?B.margin:_.NODE_SLOT_HEIGHT,e.boundingRect[3]=_.NODE_SLOT_HEIGHT}#f(){const e=[];for(const[t,n]of this.#e.entries())this.widgets?.length&&we(n)||(this.#u(n,t,!0),e.push(n));for(const[t,n]of this.#t.entries())this.#u(n,t,!1),e.push(n);return e.length?et(e,0):null}#p(e){const t=es(e),n=this.mouseOver?.[t?"inputId":"outputId"]??-1;return n===-1?null:t?this.inputs[n]:this.outputs[n]}#m(e){return this.#p(e)===e}#_(e){return e?this.mouseOver?.overWidget===e:!1}getSlotFromWidget(e){if(e)return this.inputs.find(t=>we(t)&&t.widget.name===e.name)}getWidgetFromSlot(e){if(we(e))return this.widgets?.find(t=>t.name===e.widget.name)}drawSlots(e,{fromSlot:t,colorContext:n,editorAlpha:i,lowQuality:s}){for(const a of[...this.#e,...this.#t]){const r=t&&a.isValidTarget(t),l=this.#m(a),d=!t||r,u=d&&l;(l||r||!a.isWidgetInputSlot||this.#_(this.getWidgetFromSlot(a))||a.isConnected||a.alwaysVisible)&&(e.globalAlpha=d?i:.4*i,a.draw(e,{colorContext:n,lowQuality:s,highlight:u}))}}#v(e){if(!this.widgets||!this.widgets.length)return;const t=this.bodyHeight,n=this.widgets_start_y??(this.widgets_up?0:e)+2;let i=t-n,s=0;const a=[],r=this.widgets.filter(p=>!p.hidden);for(const p of r)if(p.computeSize){const m=p.computeSize()[1]+4;p.computedHeight=m,s+=m}else if(p.computeLayoutSize){const{minHeight:m,maxHeight:g}=p.computeLayoutSize(this);a.push({minHeight:m,prefHeight:g,w:p})}else{const m=_.NODE_WIDGET_HEIGHT+4;p.computedHeight=m,s+=m}i-=s,this.freeWidgetSpace=i;const l=a.map(p=>({minSize:p.minHeight,maxSize:p.prefHeight})),d=Ms(Math.max(0,i),l);for(const[p,m]of a.entries())m.w.computedHeight=d[p];let u=n;for(const p of r)p.y=u,u+=p.computedHeight??0;if(!this.graph)throw new N;u>t&&(this.setSize([this.size[0],u]),this.graph.setDirtyCanvas(!1,!0))}#b(){if(!this.widgets)return;const e=new Map;for(const[t,n]of this.inputs.entries())we(n)&&e.set(n.widget.name,{...n,index:t});if(e.size)if(_.vueNodesMode)for(const t of this.widgets){const n=e.get(t.name);n&&this.#u(this.#e[n.index],n.index,!0)}else for(const t of this.widgets){const n=e.get(t.name);if(!n)continue;const i=this.#e[n.index],s=_.NODE_SLOT_HEIGHT*.5;i.pos=[s,t.y+s],this.#u(i,n.index,!0)}}_setConcreteSlots(){this.#e=this.inputs.map(e=>U(Be,e,this)),this.#t=this.outputs.map(e=>U(mt,e,this))}arrange(){const e=this.#f(),t=e?e[1]+e[3]-this.pos[1]:0;this.#v(t),this.#b()}drawProgressBar(e){if(!this.progress)return;const t=e.fillStyle;e.fillStyle="green",e.fillRect(0,0,this.width*this.progress,6),e.fillStyle=t}},de=class ve{static{h(this,"LGraphGroup")}static minWidth=140;static minHeight=80;static resizeLength=10;static padding=4;static defaultColour="#335";id;color;title;font;font_size=_.DEFAULT_GROUP_FONT||24;_bounding=new X(10,10,ve.minWidth,ve.minHeight);_pos=this._bounding.pos;_size=this._bounding.size;_nodes=[];_children=new Set;graph;flags={};selected;constructor(e,t){this.id=t??-1,this.title=e||"Group";const{pale_blue:n}=ce.node_colors;this.color=n?n.groupcolor:"#AAA"}setColorOption(e){e==null?delete this.color:this.color=e.groupcolor}getColorOption(){return Object.values(ce.node_colors).find(e=>e.groupcolor===this.color)??null}get pos(){return this._pos}set pos(e){!e||e.length<2||(this._pos[0]=e[0],this._pos[1]=e[1])}get size(){return this._size}set size(e){!e||e.length<2||(this._size[0]=Math.max(ve.minWidth,e[0]),this._size[1]=Math.max(ve.minHeight,e[1]))}get boundingRect(){return this._bounding}getBounding(){return this._bounding}get nodes(){return this._nodes}get titleHeight(){return this.font_size*1.4}get children(){return this._children}get pinned(){return!!this.flags.pinned}pin(e){(e===void 0?!this.pinned:e)?this.flags.pinned=!0:delete this.flags.pinned}unpin(){this.pin(!1)}configure(e){this.id=e.id,this.title=e.title,this._bounding.set(e.bounding),this.color=e.color,this.flags=e.flags||this.flags,e.font_size&&(this.font_size=e.font_size)}serialize(){const e=this._bounding;return{id:this.id,title:this.title,bounding:[...e],color:this.color,font_size:this.font_size,flags:this.flags}}draw(e,t){const{padding:n,resizeLength:i,defaultColour:s}=ve,a=this.font_size||_.DEFAULT_GROUP_FONT_SIZE,[r,l]=this._pos,[d,u]=this._size,p=this.color||s;t.globalAlpha=.25*e.editor_alpha,t.fillStyle=p,t.strokeStyle=p,t.beginPath(),t.rect(r+.5,l+.5,d,a*1.4),t.fill(),t.fillStyle=p,t.strokeStyle=p,t.beginPath(),t.rect(r+.5,l+.5,d,u),t.fill(),t.globalAlpha=e.editor_alpha,t.stroke(),t.beginPath(),t.moveTo(r+d,l+u),t.lineTo(r+d-i,l+u),t.lineTo(r+d,l+u-i),t.fill(),t.font=`${a}px ${_.GROUP_FONT}`,t.textAlign="left",t.fillText(this.title+(this.pinned?"📌":""),r+n,l+a),_.highlight_selected_group&&this.selected&&gn(t,this._bounding,{title_height:this.titleHeight,padding:n})}resize(e,t){return this.pinned?!1:(this._size[0]=Math.max(ve.minWidth,e),this._size[1]=Math.max(ve.minHeight,t),!0)}move(e,t,n=!1){if(!this.pinned&&(this._pos[0]+=e,this._pos[1]+=t,n!==!0))for(const i of this._children)i.move(e,t)}snapToGrid(e){return this.pinned?!1:xe(this.pos,e)}recomputeInsideNodes(){if(!this.graph)throw new N;const{nodes:e,reroutes:t,groups:n}=this.graph,i=this._children;this._nodes.length=0,i.clear();for(const s of e)Gi(this._bounding,s.boundingRect)&&(this._nodes.push(s),i.add(s));for(const s of t.values())We(s.pos,this._bounding)&&i.add(s);for(const s of n)en(this._bounding,s._bounding)&&i.add(s);n.sort((s,a)=>s===this?i.has(a)?-1:0:a===this&&i.has(s)?1:0)}resizeTo(e,t=10){const n=et(e,t);n!==null&&(this.pos[0]=n[0],this.pos[1]=n[1]-this.titleHeight,this.size[0]=n[2],this.size[1]=n[3]+this.titleHeight)}addNodes(e,t=10){!this._nodes&&e.length===0||this.resizeTo([...this.children,...this._nodes,...e],t)}getMenuOptions(){return[{content:this.pinned?"Unpin":"Pin",callback:h(()=>{this.pinned?this.unpin():this.pin(),this.setDirtyCanvas(!1,!0)},"callback")},null,{content:"Title",callback:ce.onShowPropertyEditor},{content:"Color",has_submenu:!0,callback:ce.onMenuNodeColors},{content:"Font size",property:"font_size",type:"Number",callback:ce.onShowPropertyEditor},null,{content:"Remove",callback:ce.onMenuNodeRemove}]}isPointInTitlebar(e,t){const n=this.boundingRect;return G(e,t,n[0],n[1],n[2],this.titleHeight)}isInResize(e,t){const n=this.boundingRect,i=n[0]+n[2],s=n[1]+n[3];return e<i&&t<s&&e-i+(t-s)>-ve.resizeLength}isPointInside=q.prototype.isPointInside;setDirtyCanvas=q.prototype.setDirtyCanvas},Ao=class{static{h(this,"FloatingRenderLink")}node;fromSlot;fromPos;fromDirection;fromSlotIndex;outputNodeId=-1;outputNode;outputSlot;outputIndex=-1;outputPos;inputNodeId=-1;inputNode;inputSlot;inputIndex=-1;inputPos;constructor(o,e,t,n,i=O.CENTER){this.network=o,this.link=e,this.toType=t,this.fromReroute=n,this.dragDirection=i;const{origin_id:s,target_id:a,origin_slot:r,target_slot:l}=e;if(s!==-1){const d=o.getNodeById(s)??void 0;if(!d)throw new Error(`Creating DraggingRenderLink for link [${e.id}] failed: Output node [${s}] not found.`);const u=d?.outputs.at(r);if(!u)throw new Error(`Creating DraggingRenderLink for link [${e.id}] failed: Output slot [${r}] not found.`);this.outputNodeId=s,this.outputNode=d,this.outputSlot=u,this.outputIndex=r,this.outputPos=d.getOutputPos(r),this.node=d,this.fromSlot=u,this.fromPos=n?.pos??this.outputPos,this.fromDirection=O.LEFT,this.dragDirection=O.RIGHT,this.fromSlotIndex=r}else{const d=o.getNodeById(a)??void 0;if(!d)throw new Error(`Creating DraggingRenderLink for link [${e.id}] failed: Input node [${a}] not found.`);const u=d?.inputs.at(l);if(!u)throw new Error(`Creating DraggingRenderLink for link [${e.id}] failed: Input slot [${l}] not found.`);this.inputNodeId=a,this.inputNode=d,this.inputSlot=u,this.inputIndex=l,this.inputPos=d.getInputPos(l),this.node=d,this.fromSlot=u,this.fromDirection=O.RIGHT,this.fromSlotIndex=l}this.fromPos=n.pos}canConnectToInput(){return this.toType==="input"}canConnectToOutput(){return this.toType==="output"}canConnectToReroute(o){if(this.toType==="input"){if(o.origin_id===this.inputNode?.id)return!1}else if(o.origin_id===this.outputNode?.id)return!1;return!0}canConnectToSubgraphInput(o){return this.toType==="output"&&o.isValidTarget(this.fromSlot)}connectToInput(o,e,t){const n=this.link;n.target_id=o.id,n.target_slot=o.inputs.indexOf(e),o.disconnectInput(o.inputs.indexOf(e)),this.fromSlot._floatingLinks?.delete(n),e._floatingLinks??=new Set,e._floatingLinks.add(n)}connectToOutput(o,e,t){const n=this.link;n.origin_id=o.id,n.origin_slot=o.outputs.indexOf(e),this.fromSlot._floatingLinks?.delete(n),e._floatingLinks??=new Set,e._floatingLinks.add(n)}connectToSubgraphInput(o,e){const t=this.link;t.origin_id=-10,t.origin_slot=o.parent.slots.indexOf(o),this.fromSlot._floatingLinks?.delete(t),o._floatingLinks??=new Set,o._floatingLinks.add(t)}connectToSubgraphOutput(o,e){const t=this.link;t.origin_id=-20,t.origin_slot=o.parent.slots.indexOf(o),this.fromSlot._floatingLinks?.delete(t),o._floatingLinks??=new Set,o._floatingLinks.add(t)}connectToRerouteInput(o,{node:e,input:t},n){const i=this.link;i.target_id=e.id,i.target_slot=e.inputs.indexOf(t),this.fromSlot._floatingLinks?.delete(i),t._floatingLinks??=new Set,t._floatingLinks.add(i),n.dispatch("input-moved",this)}connectToRerouteOutput(o,e,t,n){const i=this.link;i.origin_id=e.id,i.origin_slot=e.outputs.indexOf(t),this.fromSlot._floatingLinks?.delete(i),t._floatingLinks??=new Set,t._floatingLinks.add(i),n.dispatch("output-moved",this)}},Tt=class{static{h(this,"MovingLinkBase")}outputNodeId;outputNode;outputSlot;outputIndex;outputPos;inputNodeId;inputNode;inputSlot;inputIndex;inputPos;constructor(o,e,t,n,i=O.CENTER){this.network=o,this.link=e,this.toType=t,this.fromReroute=n,this.dragDirection=i;const{origin_id:s,target_id:a,origin_slot:r,target_slot:l}=e,d=o.getNodeById(s)??void 0;if(!d)throw new Error(`Creating MovingRenderLink for link [${e.id}] failed: Output node [${s}] not found.`);const u=d.outputs.at(r);if(!u)throw new Error(`Creating MovingRenderLink for link [${e.id}] failed: Output slot [${r}] not found.`);this.outputNodeId=s,this.outputNode=d,this.outputSlot=u,this.outputIndex=r,this.outputPos=d.getOutputPos(r);const p=o.getNodeById(a)??void 0;if(!p)throw new Error(`Creating DraggingRenderLink for link [${e.id}] failed: Input node [${a}] not found.`);const m=p.inputs.at(l);if(!m)throw new Error(`Creating DraggingRenderLink for link [${e.id}] failed: Input slot [${l}] not found.`);this.inputNodeId=a,this.inputNode=p,this.inputSlot=m,this.inputIndex=l,this.inputPos=p.getInputPos(l)}},Ow=class extends Tt{static{h(this,"MovingInputLink")}toType="input";node;fromSlot;fromPos;fromDirection;fromSlotIndex;constructor(o,e,t,n=O.CENTER){super(o,e,"input",t,n),this.node=this.outputNode,this.fromSlot=this.outputSlot,this.fromPos=t?.pos??this.outputPos,this.fromDirection=O.NONE,this.fromSlotIndex=this.outputIndex}canConnectToInput(o,e){return this.node.canConnectTo(o,e,this.outputSlot)}canConnectToOutput(){return!1}canConnectToReroute(o){return o.origin_id!==this.inputNode.id}connectToInput(o,e,t){if(e===this.inputSlot)return;this.inputNode.disconnectInput(this.inputIndex,!0);const n=this.outputNode.connectSlots(this.outputSlot,o,e,this.fromReroute?.id);return n&&t.dispatch("input-moved",this),n}connectToOutput(){throw new Error("MovingInputLink cannot connect to an output.")}connectToSubgraphInput(){throw new Error("MovingInputLink cannot connect to a subgraph input.")}connectToSubgraphOutput(o,e){const t=o.connect(this.fromSlot,this.node,this.fromReroute?.id);e?.dispatch("link-created",t)}connectToRerouteInput(o,{node:e,input:t,link:n},i,s){const{outputNode:a,outputSlot:r,fromReroute:l}=this;for(const d of s){if(d.id===this.link.parentId)break;d.totalLinks===1&&d.remove()}o.parentId=l?.id,a.connectSlots(r,e,t,n.parentId)&&i.dispatch("input-moved",this)}connectToRerouteOutput(){throw new Error("MovingInputLink cannot connect to an output.")}disconnect(){return this.inputNode.disconnectInput(this.inputIndex,!0)}},Do=class extends Tt{static{h(this,"MovingOutputLink")}toType="output";node;fromSlot;fromPos;fromDirection;fromSlotIndex;constructor(o,e,t,n=O.CENTER){super(o,e,"output",t,n),this.node=this.inputNode,this.fromSlot=this.inputSlot,this.fromPos=t?.pos??this.inputPos,this.fromDirection=O.LEFT,this.fromSlotIndex=this.inputIndex}canConnectToInput(){return!1}canConnectToOutput(o,e){return o.canConnectTo(this.node,this.inputSlot,e)}canConnectToReroute(o){return o.origin_id!==this.outputNode.id}canConnectToSubgraphInput(o){return o.isValidTarget(this.fromSlot)}connectToInput(){throw new Error("MovingOutputLink cannot connect to an input.")}connectToOutput(o,e,t){if(e===this.outputSlot)return;const n=o.connectSlots(e,this.inputNode,this.inputSlot,this.link.parentId);return n&&t.dispatch("output-moved",this),n}connectToSubgraphInput(o,e){const t=o.connect(this.fromSlot,this.node,this.fromReroute?.id);e?.dispatch("link-created",t)}connectToSubgraphOutput(){throw new Error("MovingOutputLink cannot connect to a subgraph output.")}connectToRerouteInput(){throw new Error("MovingOutputLink cannot connect to an input.")}connectToRerouteOutput(o,e,t,n){const{inputNode:i,inputSlot:s,fromReroute:a}=this,r=o?.floating?.slotType==="output";a?a.parentId=o.id:this.link.parentId=o.id,e.connectSlots(t,i,s,this.link.parentId),r&&o.removeAllFloatingLinks(),n.dispatch("output-moved",this)}disconnect(){return this.outputNode.disconnectOutput(this.outputIndex,this.inputNode)}},dt=class{static{h(this,"ToInputFromIoNodeLink")}toType="input";fromSlotIndex;fromPos;fromDirection=O.RIGHT;existingLink;constructor(o,e,t,n,i=O.CENTER,s){this.network=o,this.node=e,this.fromSlot=t,this.fromReroute=n,this.dragDirection=i;const a=e.slots.indexOf(t);if(a===-1&&t!==e.emptySlot)throw new Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);this.fromSlotIndex=a,this.fromPos=n?n.pos:t.pos,this.existingLink=s}canConnectToInput(o,e){return this.node.canConnectTo(o,e,this.fromSlot)}canConnectToOutput(){return!1}connectToInput(o,e,t){const{fromSlot:n,fromReroute:i,existingLink:s}=this,a=n.connect(e,o,i?.id);if(s){const{input:r,inputNode:l}=s.resolve(this.network);l&&r&&this.node._disconnectNodeInput(l,r,s),t.dispatch("input-moved",this)}else t.dispatch("link-created",a)}connectToSubgraphOutput(){throw new Error("Not implemented")}connectToRerouteInput(o,{node:e,input:t,link:n},i,s){const{fromSlot:a,fromReroute:r}=this,l=r?.floating?.slotType==="output";o.parentId=r?.id;const d=a.connect(t,e,n.parentId);l&&r.removeAllFloatingLinks();for(const u of s){if(u.id===r?.id)break;if(u.removeLink(n),u.totalLinks===0)if(n.isFloating)u.remove();else{const p=n.toFloating("output",u.id);this.network.addFloatingLink(p),u.floating={slotType:"output"}}}this.existingLink?i.dispatch("input-moved",this):i.dispatch("link-created",d)}connectToOutput(){throw new Error("ToInputRenderLink cannot connect to an output.")}connectToSubgraphInput(){throw new Error("ToInputRenderLink cannot connect to a subgraph input.")}connectToRerouteOutput(){throw new Error("ToInputRenderLink cannot connect to an output.")}disconnect(){if(!this.existingLink)return!1;const{input:o,inputNode:e}=this.existingLink.resolve(this.network);return!e||!o?!1:(this.node._disconnectNodeInput(e,o,this.existingLink),!0)}},ze=class{static{h(this,"ToInputRenderLink")}toType="input";fromPos;fromSlotIndex;fromDirection=O.RIGHT;constructor(o,e,t,n,i=O.CENTER){this.network=o,this.node=e,this.fromSlot=t,this.fromReroute=n,this.dragDirection=i;const s=e.outputs.indexOf(t);if(s===-1)throw new Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);this.fromSlotIndex=s,this.fromPos=n?n.pos:this.node.getOutputPos(s)}canConnectToInput(o,e){return this.node.canConnectTo(o,e,this.fromSlot)}canConnectToOutput(){return!1}connectToInput(o,e,t){const{node:n,fromSlot:i,fromReroute:s}=this;if(o===n)return;const a=n.connectSlots(i,o,e,s?.id);t.dispatch("link-created",a)}connectToSubgraphOutput(o,e){const t=o.connect(this.fromSlot,this.node,this.fromReroute?.id);e.dispatch("link-created",t)}connectToRerouteInput(o,{node:e,input:t,link:n},i,s){const{node:a,fromSlot:r,fromReroute:l}=this,d=l?.floating?.slotType==="output";o.parentId=l?.id;const u=a.connectSlots(r,e,t,n.parentId);d&&l.removeAllFloatingLinks();for(const p of s){if(p.id===l?.id)break;if(p.removeLink(n),p.totalLinks===0)if(n.isFloating)p.remove();else{const m=n.toFloating("output",p.id);this.network.addFloatingLink(m),p.floating={slotType:"output"}}}i.dispatch("link-created",u)}connectToOutput(){throw new Error("ToInputRenderLink cannot connect to an output.")}connectToSubgraphInput(){throw new Error("ToInputRenderLink cannot connect to a subgraph input.")}connectToRerouteOutput(){throw new Error("ToInputRenderLink cannot connect to an output.")}},Vt=class{static{h(this,"ToOutputFromIoNodeLink")}toType="output";fromPos;fromSlotIndex;fromDirection=O.LEFT;constructor(o,e,t,n,i=O.CENTER){this.network=o,this.node=e,this.fromSlot=t,this.fromReroute=n,this.dragDirection=i;const s=e.slots.indexOf(t);if(s===-1&&t!==e.emptySlot)throw new Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);this.fromSlotIndex=s,this.fromPos=n?n.pos:t.pos}canConnectToInput(){return!1}canConnectToOutput(o,e){return this.node.canConnectTo(o,this.fromSlot,e)}canConnectToReroute(o){return o.origin_id!==this.node.id}connectToOutput(o,e,t){const{fromSlot:n,fromReroute:i}=this,s=n.connect(e,o,i?.id);t.dispatch("link-created",s)}connectToSubgraphInput(){throw new Error("Not implemented")}connectToRerouteOutput(o,e,t,n){const{fromSlot:i}=this,s=i.connect(t,e,o?.id);n.dispatch("link-created",s)}connectToInput(){throw new Error("ToOutputRenderLink cannot connect to an input.")}connectToSubgraphOutput(){throw new Error("ToOutputRenderLink cannot connect to a subgraph output.")}connectToRerouteInput(){throw new Error("ToOutputRenderLink cannot connect to an input.")}},xn=class{static{h(this,"ToOutputRenderLink")}toType="output";fromPos;fromSlotIndex;fromDirection=O.LEFT;constructor(o,e,t,n,i=O.CENTER){this.network=o,this.node=e,this.fromSlot=t,this.fromReroute=n,this.dragDirection=i;const s=e.inputs.indexOf(t);if(s===-1)throw new Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);this.fromSlotIndex=s,this.fromPos=n?n.pos:this.node.getInputPos(s)}canConnectToInput(){return!1}canConnectToOutput(o,e){return this.node.canConnectTo(o,this.fromSlot,e)}canConnectToReroute(o){return o.origin_id!==this.node.id}canConnectToSubgraphInput(o){return o.isValidTarget(this.fromSlot)}connectToOutput(o,e,t){const{node:n,fromSlot:i,fromReroute:s}=this;if(!n)return;const a=o.connectSlots(e,n,i,s?.id);t.dispatch("link-created",a)}connectToSubgraphInput(o,e){const t=o.connect(this.fromSlot,this.node,this.fromReroute?.id);e?.dispatch("link-created",t)}connectToRerouteOutput(o,e,t,n){const{node:i,fromSlot:s}=this,a=e.connectSlots(t,i,s,o?.id);n.dispatch("link-created",a)}connectToInput(){throw new Error("ToOutputRenderLink cannot connect to an input.")}connectToSubgraphOutput(){throw new Error("ToOutputRenderLink cannot connect to a subgraph output.")}connectToRerouteInput(){throw new Error("ToOutputRenderLink cannot connect to an input.")}},Pw=class extends xn{static{h(this,"ToOutputFromRerouteLink")}constructor(o,e,t,n,i){super(o,e,t,n),this.fromReroute=n,this.linkConnector=i}canConnectToReroute(){return!1}connectToOutput(o,e){const t=new ze(this.network,o,e);this.linkConnector._connectOutputToReroute(this.fromReroute,t)}},Mw=class{static{h(this,"LinkConnector")}state={connectingTo:void 0,multi:!1,draggingExistingLinks:!1,snapLinksPos:void 0};events=new Et;renderLinks=[];inputLinks=[];outputLinks=[];floatingLinks=[];hiddenReroutes=new Set;overWidget;overWidgetType;overReroute;#e;constructor(o){this.#e=o}get isConnecting(){return this.state.connectingTo!==void 0}get draggingExistingLinks(){return this.state.draggingExistingLinks}moveInputLink(o,e){if(this.isConnecting)throw new Error("Already dragging links.");const{state:t,inputLinks:n,renderLinks:i}=this,s=e.link;if(s==null){const a=e._floatingLinks?.values().next().value;if(a?.parentId==null)return;try{const r=o.reroutes.get(a.parentId);if(!r)throw new Error(`Invalid reroute id: [${a.parentId}] for floating link id: [${a.id}].`);const l=new Ao(o,a,"input",r);if(this.events.dispatch("before-move-input",l)===!1)return;i.push(l)}catch(r){console.warn(`Could not create render link for link id: [${a.id}].`,a,r)}a._dragging=!0,this.floatingLinks.push(a)}else{const a=o.links.get(s);if(!a)return;if(a.origin_id===-10){const r=o.inputNode?.slots[a.origin_slot];if(!r){console.warn(`Could not find subgraph input for slot [${a.origin_slot}]`);return}try{const l=o.getReroute(a.parentId),d=new dt(o,o.inputNode,r,l,O.CENTER,a);i.push(d),this.listenUntilReset("input-moved",()=>{a.disconnect(o,"input")})}catch(l){console.warn(`Could not create render link for subgraph input link id: [${a.id}].`,a,l);return}a._dragging=!0,n.push(a)}else{try{const r=new Ow(o,a,o.getReroute(a.parentId));if(this.events.dispatch("before-move-input",r)===!1)return;i.push(r),this.listenUntilReset("input-moved",l=>{"link"in l.detail&&l.detail.link&&l.detail.link.disconnect(o,"output")})}catch(r){console.warn(`Could not create render link for link id: [${a.id}].`,a,r);return}a._dragging=!0,n.push(a)}}t.connectingTo="input",t.draggingExistingLinks=!0,this.#n(!1)}moveOutputLink(o,e){if(this.isConnecting)throw new Error("Already dragging links.");const{state:t,renderLinks:n}=this;if(e._floatingLinks?.size)for(const i of e._floatingLinks.values())try{const s=z.getFirstReroute(o,i);if(!s)throw new Error(`Invalid reroute id: [${i.parentId}] for floating link id: [${i.id}].`);const a=new Ao(o,i,"output",s);if(this.events.dispatch("before-move-output",a)===!1)continue;n.push(a),this.floatingLinks.push(i)}catch(s){console.warn(`Could not create render link for link id: [${i.id}].`,i,s)}if(e.links?.length)for(const i of e.links){const s=o.links.get(i);if(!s)continue;const a=z.getFirstReroute(o,s);a?(a._dragging=!0,this.hiddenReroutes.add(a)):s._dragging=!0,this.outputLinks.push(s);try{if(s.target_id===-20){if(!(o instanceof De)){console.warn("Subgraph output link found in non-subgraph network.");continue}const l=o.outputs.at(s.target_slot);if(!l)throw new Error("No subgraph output found for link.");const d=new Vt(o,o.outputNode,l);d.fromDirection=O.NONE,n.push(d);continue}const r=new Do(o,s,a,O.RIGHT);if(this.events.dispatch("before-move-output",r)===!1)continue;n.push(r)}catch(r){console.warn(`Could not create render link for link id: [${s.id}].`,s,r);continue}}n.length!==0&&(t.draggingExistingLinks=!0,t.multi=!0,t.connectingTo="output",this.#n(!0))}dragNewFromOutput(o,e,t,n){if(this.isConnecting)throw new Error("Already dragging links.");const{state:i}=this,s=new ze(o,e,t,n);this.renderLinks.push(s),i.connectingTo="input",this.#n(!1)}dragNewFromInput(o,e,t,n){if(this.isConnecting)throw new Error("Already dragging links.");const{state:i}=this,s=new xn(o,e,t,n);this.renderLinks.push(s),i.connectingTo="output",this.#n(!0)}dragNewFromSubgraphInput(o,e,t,n){if(this.isConnecting)throw new Error("Already dragging links.");const i=new dt(o,e,t,n);this.renderLinks.push(i),this.state.connectingTo="input",this.#n(!1)}dragNewFromSubgraphOutput(o,e,t,n){if(this.isConnecting)throw new Error("Already dragging links.");const i=new Vt(o,e,t,n);this.renderLinks.push(i),this.state.connectingTo="output",this.#n(!0)}dragFromReroute(o,e){if(this.isConnecting)throw new Error("Already dragging links.");const t=e.firstLink??e.firstFloatingLink;if(!t){console.warn("No link found for reroute.");return}if(t.origin_id===-10){if(!(o instanceof De)){console.warn("Subgraph input link found in non-subgraph network.");return}const a=o.inputs.at(t.origin_slot);if(!a)throw new Error("No subgraph input found for link.");const r=new dt(o,o.inputNode,a,e);r.fromDirection=O.NONE,this.renderLinks.push(r),this.state.connectingTo="input",this.#n(!1);return}const n=o.getNodeById(t.origin_id);if(!n){console.warn("No output node found for link.",t);return}const i=n.outputs.at(t.origin_slot);if(!i){console.warn("No output slot found for link.",t);return}const s=new ze(o,n,i,e);s.fromDirection=O.NONE,this.renderLinks.push(s),this.state.connectingTo="input",this.#n(!1)}dragFromRerouteToOutput(o,e){if(this.isConnecting)throw new Error("Already dragging links.");const t=e.firstLink??e.firstFloatingLink;if(!t){console.warn("No link found for reroute.");return}if(t.target_id===-20){if(!(o instanceof De)){console.warn("Subgraph output link found in non-subgraph network.");return}const a=o.outputs.at(t.target_slot);if(!a)throw new Error("No subgraph output found for link.");const r=new Vt(o,o.outputNode,a,e);r.fromDirection=O.NONE,this.renderLinks.push(r),this.state.connectingTo="output",this.#n(!1);return}const n=o.getNodeById(t.target_id);if(!n){console.warn("No input node found for link.",t);return}const i=n.inputs.at(t.target_slot);if(!i){console.warn("No input slot found for link.",t);return}const s=new Pw(o,n,i,e,this);s.fromDirection=O.LEFT,this.renderLinks.push(s),this.state.connectingTo="output",this.#n(!0)}dragFromLinkSegment(o,e){if(this.isConnecting)throw new Error("Already dragging links.");const{state:t}=this;if(e.origin_id==null||e.origin_slot==null)return;const n=o.getNodeById(e.origin_id);if(!n)return;const i=n.outputs.at(e.origin_slot);if(!i)return;const s=new ze(o,n,i,o.getReroute(e.parentId));s.fromDirection=O.NONE,this.renderLinks.push(s),t.connectingTo="input",this.#n(!1)}dropLinks(o,e){if(!(!this.isConnecting&&this.events.dispatch("before-drop-links",{renderLinks:this.renderLinks,event:e})===!1))try{const{canvasX:t,canvasY:n}=e,i=o.getIoNodeOnPos?.(t,n);if(i){this.dropOnIoNode(i,e);return}const s=o.getNodeOnPos(t,n)??void 0;if(s)this.dropOnNode(s,e);else{const a=o.getRerouteOnPos(t,n);a&&this.isRerouteValidDrop(a)?this.dropOnReroute(a,e):this.dropOnNothing(e)}}finally{this.events.dispatch("after-drop-links",{renderLinks:this.renderLinks,event:e})}}dropOnIoNode(o,e){const{renderLinks:t,state:n}=this,{connectingTo:i}=n,{canvasX:s,canvasY:a}=e;if(i==="input"&&o instanceof xt){const r=o.getSlotInPosition(s,a);if(!r){this.dropOnNothing(e);return}let l=r;for(const d of t)if(d.connectToSubgraphOutput(l,this.events),r instanceof kn&&o.slots.length>0){const u=o.slots[o.slots.length-1],p=t[t.indexOf(d)+1];p&&d.fromSlot.type===p.fromSlot.type?l=u:l=r}}else if(i==="output"&&o instanceof Nt){const r=o.getSlotInPosition(s,a);if(!r){this.dropOnNothing(e);return}let l=r;for(const d of t){if("canConnectToSubgraphInput"in d&&!d.canConnectToSubgraphInput(l)){console.warn("Invalid connection type",d.fromSlot.type,"->",l.type);continue}if(d.connectToSubgraphInput(l,this.events),r instanceof bn&&o.slots.length>0){const u=o.slots[o.slots.length-1],p=t[t.indexOf(d)+1];p&&d.fromSlot.type===p.fromSlot.type?l=u:l=r}}}else console.error("Invalid connectingTo state &/ ioNode",i,o)}dropOnNode(o,e){const{renderLinks:t,state:n}=this,{connectingTo:i}=n,{canvasX:s,canvasY:a}=e;if(!t.every(r=>r.node===o)){if(i==="output"){const r=o.getOutputOnPos([s,a]);r?this.#o(o,r):this.connectToNode(o,e)}else if(i==="input"){const r=o.getInputOnPos([s,a])??o.getSlotFromWidget(this.overWidget);r?this.#t(o,r):this.connectToNode(o,e)}}}dropOnReroute(o,e){if(this.events.dispatch("dropped-on-reroute",{reroute:o,event:e})!==!1){if(this.state.connectingTo==="input"){if(this.renderLinks.length!==1)throw new Error(`Attempted to connect ${this.renderLinks.length} input links to a reroute.`);const t=this.renderLinks[0];this._connectOutputToReroute(o,t);return}for(const t of this.renderLinks){if(t.toType!=="output")continue;const n=o.findSourceOutput();if(!n)continue;const{node:i,output:s}=n;t.canConnectToOutput(i,s)&&t.connectToRerouteOutput(o,i,s,this.events)}}}_connectOutputToReroute(o,e){const t=o.findTargetInputs();if(!t?.length)return;const n=o.getReroutes();if(n===null)throw new Error("Reroute loop detected.");const i=n.slice(0,-1).reverse();if(e instanceof ze){const{node:a,fromSlot:r,fromSlotIndex:l,fromReroute:d}=e;if(o.setFloatingLinkOrigin(a,r,l),d!=null)for(const u of i){if(u.id===d.id)break;for(const p of o.floatingLinkIds)u.floatingLinkIds.delete(p)}}const s=t.filter(a=>e.toType==="input"&&Oo(e,a.node,a.input,o));for(const a of s)e.connectToRerouteInput(o,a,this.events,i)}dropOnNothing(o){this.events.dispatch("dropped-on-canvas",o)!==!1&&this.disconnectLinks()}disconnectLinks(){for(const o of this.renderLinks)(o instanceof Tt||o instanceof dt)&&o.disconnect()}connectToNode(o,e){const{state:{connectingTo:t}}=this;if(this.events.dispatch("dropped-on-node",{node:o,event:e})===!1)return;const n=this.renderLinks[0];if(n){if(t==="output"){const i=o.findOutputByType(n.fromSlot.type)?.slot;if(i===void 0){console.warn(`Could not find slot for link type: [${n.fromSlot.type}].`);return}this.#o(o,i)}else if(t==="input"){const i=o.findInputByType(n.fromSlot.type)?.slot;if(i===void 0){console.warn(`Could not find slot for link type: [${n.fromSlot.type}].`);return}this.#t(o,i)}}}#t(o,e){for(const t of this.renderLinks)t.canConnectToInput(o,e)&&t.connectToInput(o,e,this.events)}#o(o,e){for(const t of this.renderLinks){if(!t.canConnectToOutput(o,e)){t instanceof Do&&t.link.parentId!==void 0&&t.outputNode.connectSlots(t.outputSlot,t.inputNode,t.inputSlot,void 0);continue}t.connectToOutput(o,e,this.events)}}isInputValidDrop(o,e){return this.renderLinks.some(t=>t.canConnectToInput(o,e))}isNodeValidDrop(o){return this.state.connectingTo==="output"?o.outputs.some(e=>this.renderLinks.some(t=>t.canConnectToOutput(o,e))):o.inputs.some(e=>this.renderLinks.some(t=>t.canConnectToInput(o,e)))}isSubgraphInputValidDrop(o){return this.renderLinks.some(e=>"canConnectToSubgraphInput"in e&&e.canConnectToSubgraphInput(o))}isRerouteValidDrop(o){if(this.state.connectingTo==="input"){const e=o.findTargetInputs();if(!e?.length)return!1;for(const{node:t,input:n}of e)for(const i of this.renderLinks)if(i.toType==="input"&&Oo(i,t,n,o))return!0}else{const e=o.findSourceOutput();if(!e)return!1;const{node:t,output:n}=e;for(const i of this.renderLinks)if(i.toType==="output"&&i.canConnectToReroute(o)&&i.canConnectToOutput(t,n))return!0}return!1}#n(o){const e=this.renderLinks.map(t=>{const n=o?t.fromSlot:null,i=o?null:t.fromSlot,s=t instanceof Tt?t.link?.parentId:t.fromReroute?.id;return{node:t.node,slot:t.fromSlotIndex,input:n,output:i,pos:t.fromPos,afterRerouteId:s}});this.#e(e)}export(o){return{renderLinks:[...this.renderLinks],inputLinks:[...this.inputLinks],outputLinks:[...this.outputLinks],floatingLinks:[...this.floatingLinks],state:{...this.state},network:o}}listenUntilReset(o,e,t){this.events.addEventListener(o,e,t),this.events.addEventListener("reset",()=>this.events.removeEventListener(o,e),{once:!0})}reset(o=!1){if(this.events.dispatch("reset",o)===!1)return;const{state:e,outputLinks:t,inputLinks:n,hiddenReroutes:i,renderLinks:s,floatingLinks:a}=this;if(!(!o&&e.connectingTo===void 0)){e.connectingTo=void 0;for(const r of t)delete r._dragging;for(const r of n)delete r._dragging;for(const r of a)delete r._dragging;for(const r of i)delete r._dragging;s.length=0,n.length=0,t.length=0,a.length=0,i.clear(),e.multi=!1,e.draggingExistingLinks=!1,e.snapLinksPos=void 0}}};function Oo(o,e,t,n){const{fromReroute:i}=o;if(!o.canConnectToInput(e,t)||i?.id===n.id||i?.getReroutes()?.includes(n))return!1;if(o instanceof ze){if(n.parentId==null){if(n.firstLink?.hasOrigin(o.node.id,o.fromSlotIndex))return!1}else if(o.fromReroute?.id===n.parentId)return!1}return!0}h(Oo,"canConnectInputLinkToReroute");var Qt=class extends Error{static{h(this,"RecursionError")}constructor(o){super(o),this.name="RecursionError"}},ut=class extends Error{static{h(this,"InvalidLinkError")}constructor(o="Attempted to access a link that was invalid.",e){super(o,{cause:e}),this.name="InvalidLinkError"}},Ut=class extends Error{static{h(this,"SlotIndexError")}constructor(o="Attempted to access a slot that was out of bounds.",e){super(o,{cause:e}),this.name="SlotIndexError"}},Po=class{static{h(this,"ExecutableNodeDTO")}graph;inputs;#e;get id(){return this.#e}get type(){return this.node.type}get title(){return this.node.title}get mode(){return this.node.mode}get comfyClass(){return this.node.comfyClass}get isVirtualNode(){return this.node.isVirtualNode}get widgets(){return this.node.widgets}get subgraphId(){return this.subgraphNode?.subgraph.id}constructor(o,e,t,n){if(this.node=o,this.subgraphNodePath=e,this.nodesByExecutionId=t,this.subgraphNode=n,!o.graph)throw new N;this.#e=[...this.subgraphNodePath,this.node.id].join(":"),this.graph=o.graph,this.inputs=this.node.inputs.map(i=>({linkId:i.link,name:i.name,type:i.type})),this.node.applyToGraph&&(this.applyToGraph=(...i)=>this.node.applyToGraph?.(...i))}getInnerNodes(){return this.node.isSubgraphNode()?this.node.getInnerNodes(this.nodesByExecutionId,this.subgraphNodePath):[this]}resolveInput(o,e=new Set,t){const n=`${this.subgraphNode?.subgraph.id}:${this.node.id}[I]${o}`;if(e.has(n))throw new Qt(`Circular reference detected while resolving input ${o} of node ${`${this.node.id}${this.node.title?` (${this.node.title})`:""}`}${this.subgraphNodePath.length>0?` at path ${this.subgraphNodePath.join(":")}`:""}. This creates an infinite loop in link resolution. UniqueID: [${n}]`);e.add(n);const i=this.inputs.at(o);if(!i)throw new Ut(`No input found for flattened id [${this.id}] slot [${o}]`);if(i.linkId==null)return;const s=this.graph.getLink(i.linkId);if(!s)throw new ut(`No link found in parent graph for id [${this.id}] slot [${o}] ${i.name}`);const{subgraphNode:a}=this;if(a&&s.originIsIoNode){const u=a.inputs.at(s.origin_slot);if(!u)throw new Ut(`No input found for slot [${s.origin_slot}] ${i.name}`);const p=u.link;if(p==null){const y=a.getWidgetFromSlot(u);return y?{node:this,origin_id:this.id,origin_slot:-1,widgetInfo:{value:y.value}}:void 0}const m=a.graph.getLink(p);if(!m)throw new ut(`No outer link found for slot [${s.origin_slot}] ${i.name}`);const g=this.subgraphNodePath.join(":"),f=this.nodesByExecutionId.get(g);if(!f)throw new Error(`No subgraph node DTO found for id [${g}]`);return f.resolveInput(m.target_slot,e)}const r=this.graph.getNodeById(s.origin_id);if(!r)throw new ut(`No input node found for id [${this.id}] slot [${o}] ${i.name}`);const l=[...this.subgraphNodePath,r.id].join(":"),d=this.nodesByExecutionId.get(l);if(!d)throw new Error(`No output node DTO found for id [${l}]`);return d.resolveOutput(s.origin_slot,t??i.type,e)}resolveOutput(o,e,t){const n=`${this.subgraphNode?.subgraph.id}:${this.node.id}[O]${o}`;if(t.has(n))throw new Qt(`Circular reference detected while resolving output ${o} of node ${`${this.node.id}${this.node.title?` (${this.node.title})`:""}`}${this.subgraphNodePath.length>0?` at path ${this.subgraphNodePath.join(":")}`:""}. This creates an infinite loop in link resolution. UniqueID: [${n}]`);if(t.add(n),this.mode===H.BYPASS){const s=this.#t(o,e);if(s===-1){console.warn(`[ExecutableNodeDTO.resolveOutput] No input types match type [${e}] for id [${this.id}] slot [${o}]`,this);return}return this.resolveInput(s,t)}const{node:i}=this;if(i.isSubgraphNode())return this.#o(o,e,t);if(i.isVirtualNode){const s=this.node.getInputLink(o);if(s){const{inputNode:a}=s.resolve(this.graph);if(!a)throw new ut(`Virtual node failed to resolve parent [${this.id}] slot [${o}]`);const r=[...this.subgraphNodePath,a.id].join(":"),l=this.nodesByExecutionId.get(r);if(!l)throw new Error(`No input node DTO found for id [${a.id}]`);return l.resolveInput(s.target_slot,t,e)}return}return{node:this,origin_id:this.id,origin_slot:o}}#t(o,e){const{inputs:t}=this,n=t[o],i=this.node.outputs[o].type;if(e==="*"||e==="")return t.length>o?o:0;if(n&&_.isValidConnection(n.type,i)&&_.isValidConnection(n.type,e))return o;const s=t.findIndex(a=>a.type===e);return s!==-1?s:t.findIndex(a=>_.isValidConnection(a.type,i)&&_.isValidConnection(a.type,e))}#o(o,e,t){const{node:n}=this,i=n.outputs.at(o);if(!i)throw new Ut(`No output found for flattened id [${this.id}] slot [${o}]`);if(!n.isSubgraphNode())throw new TypeError(`Node is not a subgraph node: ${n.id}`);const s=n.resolveSubgraphOutputLink(o);if(!s)return;const a=s.outputNode;if(!a)throw new Error(`No output node found for id [${this.id}] slot [${o}] ${i.name}`);const r=[...this.subgraphNodePath,n.id,a.id].join(":"),l=this.nodesByExecutionId.get(r);if(!l)throw new Error(`No inner node DTO found for id [${r}]`);return l.resolveOutput(s.link.origin_slot,e,t)}},An=new Image;An.src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' width='16' height='16'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3E%3Cpath stroke='white' stroke-linecap='round' stroke-width='1.3' d='M9.18613 3.09999H6.81377M9.18613 12.9H7.55288c-3.08678 0-5.35171-2.99581-4.60305-6.08843l.3054-1.26158M14.7486 2.1721l-.5931 2.45c-.132.54533-.6065.92789-1.1508.92789h-2.2993c-.77173 0-1.33797-.74895-1.1508-1.5221l.5931-2.45c.132-.54533.6065-.9279 1.1508-.9279h2.2993c.7717 0 1.3379.74896 1.1508 1.52211Zm-8.3033 0-.59309 2.45c-.13201.54533-.60646.92789-1.15076.92789H2.4021c-.7717 0-1.33793-.74895-1.15077-1.5221l.59309-2.45c.13201-.54533.60647-.9279 1.15077-.9279h2.29935c.77169 0 1.33792.74896 1.15076 1.52211Zm8.3033 9.8-.5931 2.45c-.132.5453-.6065.9279-1.1508.9279h-2.2993c-.77173 0-1.33797-.749-1.1508-1.5221l.5931-2.45c.132-.5453.6065-.9279 1.1508-.9279h2.2993c.7717 0 1.3379.7489 1.1508 1.5221Z'/%3E%3C/svg%3E %3C/svg%3E";var gt=class extends q{static{h(this,"SubgraphNode")}type;isVirtualNode=!0;get rootGraph(){return this.graph.rootGraph}get displayType(){return"Subgraph node"}isSubgraphNode(){return!0}widgets=[];#e=new AbortController;constructor(o,e,t){super(e.name,e.id),this.graph=o,this.subgraph=e;const n=this.subgraph.events,{signal:i}=this.#e;n.addEventListener("input-added",s=>{const a=s.detail.input,{name:r,type:l}=a,d=this.inputs.find(p=>p.name==r);if(d){const p=a.linkIds[0],{inputNode:m,input:g}=e.links[p].resolve(e),f=m?.widgets?.find?.(y=>y.name==r);f&&this.#o(a,d,f,g?.widget);return}const u=this.addInput(r,l);this.#t(a,u)},{signal:i}),n.addEventListener("removing-input",s=>{const a=s.detail.input._widget;a&&this.ensureWidgetRemoved(a),this.removeInput(s.detail.index),this.setDirtyCanvas(!0,!0)},{signal:i}),n.addEventListener("output-added",s=>{const{name:a,type:r}=s.detail.output;this.addOutput(a,r)},{signal:i}),n.addEventListener("removing-output",s=>{this.removeOutput(s.detail.index),this.setDirtyCanvas(!0,!0)},{signal:i}),n.addEventListener("renaming-input",s=>{const{index:a,newName:r}=s.detail,l=this.inputs.at(a);if(!l)throw new Error("Subgraph input not found");l.label=r,l._widget&&(l._widget.label=r)},{signal:i}),n.addEventListener("renaming-output",s=>{const{index:a,newName:r}=s.detail,l=this.outputs.at(a);if(!l)throw new Error("Subgraph output not found");l.label=r},{signal:i}),this.type=e.id,this.configure(t),this.addTitleButton({name:"enter_subgraph",text:"",yOffset:0,xOffset:-10,fontSize:16})}onTitleButtonClick(o,e){o.name==="enter_subgraph"?e.openSubgraph(this.subgraph,this):super.onTitleButtonClick(o,e)}#t(o,e){e._listenerController&&typeof e._listenerController.abort=="function"&&e._listenerController.abort(),e._listenerController=new AbortController;const{signal:t}=e._listenerController;o.events.addEventListener("input-connected",n=>{if(e._widget)return;const i=o._widget;if(!i)return;const s=n.detail.input.widget;this.#o(o,e,i,s)},{signal:t}),o.events.addEventListener("input-disconnected",()=>{o.getConnectedWidgets().length>0||(this.removeWidgetByName(e.name),delete e.pos,delete e.widget,e._widget=void 0)},{signal:t})}configure(o){for(const e of this.inputs)e._listenerController&&typeof e._listenerController.abort=="function"&&e._listenerController.abort();this.inputs.length=0,this.inputs.push(...this.subgraph.inputNode.slots.map(e=>new Be({name:e.name,localized_name:e.localized_name,label:e.label,type:e.type,link:null},this))),this.outputs.length=0,this.outputs.push(...this.subgraph.outputNode.slots.map(e=>new mt({name:e.name,localized_name:e.localized_name,label:e.label,type:e.type,links:null},this))),super.configure(o)}_internalConfigureAfterSlots(){this.widgets.length=0;for(const o of this.inputs){const e=this.subgraph.inputNode.slots.find(t=>t.name===o.name);if(!e){console.warn(`[SubgraphNode.configure] No subgraph input found for input ${o.name}, skipping`);continue}this.#t(e,o);for(const t of e.linkIds){const n=this.subgraph.getLink(t);if(!n){console.warn(`[SubgraphNode.configure] No link found for link ID ${t}`,this);continue}const{inputNode:i}=n.resolve(this.subgraph);if(!i){console.warn("Failed to resolve inputNode",n,this);continue}const s=i.inputs.find(r=>r.link===t);if(!s){console.warn("Failed to find corresponding input",n,i);continue}const a=i.getWidgetFromSlot(s);if(a){this.#o(e,o,a,s.widget);break}}}}#o(o,e,t,n){const i=Ct(t,this).createCopyForNode(this);t instanceof En&&(i.options.nodeType??=t.node.type),Object.assign(i,{get name(){return o.name},set name(a){console.warn("Promoted widget: setting name is not allowed",this,a)},get localized_name(){return o.localized_name},set localized_name(a){console.warn("Promoted widget: setting localized_name is not allowed",this,a)},get label(){return o.label},set label(a){console.warn("Promoted widget: setting label is not allowed",this,a)},get tooltip(){return t.tooltip},set tooltip(a){console.warn("Promoted widget: setting tooltip is not allowed",this,a)}});const s=this.inputs.filter(a=>a.widget).length;this.widgets.splice(s,0,i),this.subgraph.events.dispatch("widget-promoted",{widget:i,subgraphNode:this}),e.widget??={name:o.name},e.widget.name=o.name,n&&Object.setPrototypeOf(e.widget,n),e._widget=i}addInput(o,e,t={}){return super.addInput(o,e,t)}getInputLink(o){const e=this.subgraph.outputNode.slots[o].getLinks().at(0);if(!e)return console.warn(`SubgraphNode.getInputLink: no inner link found for slot ${o}`),null;const t=z.create(e);return t.origin_id=`${this.id}:${e.origin_id}`,t.origin_slot=e.origin_slot,t}resolveSubgraphInputLinks(o){const e=this.subgraph.inputNode.slots[o],t=e.getLinks();return t.length===0?(console.warn(`[SubgraphNode.resolveSubgraphInputLinks] No inner links found for input slot [${o}] ${e.name}`,this),[]):t.map(n=>n.resolve(this.subgraph))}resolveSubgraphOutputLink(o){const e=this.subgraph.outputNode.slots[o],t=e.getLinks().at(0);if(t)return t.resolve(this.subgraph);console.warn(`[SubgraphNode.resolveSubgraphOutputLink] No inner link found for output slot [${o}] ${e.name}`,this)}getInnerNodes(o,e=[],t=[],n=new Set){if(n.has(this)){const r=`${this.id}${this.title?` (${this.title})`:""}`,l=`'${this.subgraph.name||"Unnamed Subgraph"}'`,d=e.length;throw new Qt(`Circular reference detected at depth ${d} in node ${r} of subgraph ${l}. This creates an infinite loop in the subgraph hierarchy.`)}n.add(this);const i=[...e,this.id],s=this.graph.rootGraph.resolveSubgraphIdPath(e).at(-1),a=new Po(this,e,o,s);o.set(a.id,a);for(const r of this.subgraph.nodes)if("getInnerNodes"in r&&r.getInnerNodes)r.getInnerNodes(o,i,t,new Set(n));else{const l=new Po(r,i,o,this);o.set(l.id,l),t.push(l)}return t}removeWidgetByName(o){const e=this.widgets.find(t=>t.name===o);e&&this.subgraph.events.dispatch("widget-demoted",{widget:e,subgraphNode:this}),super.removeWidgetByName(o)}ensureWidgetRemoved(o){this.widgets.includes(o)&&this.subgraph.events.dispatch("widget-demoted",{widget:o,subgraphNode:this}),super.ensureWidgetRemoved(o)}onRemoved(){this.#e.abort();for(const o of this.widgets)"isProxyWidget"in o&&o.isProxyWidget||this.subgraph.events.dispatch("widget-demoted",{widget:o,subgraphNode:this});for(const o of this.inputs)o._listenerController&&typeof o._listenerController.abort=="function"&&o._listenerController.abort()}drawTitleBox(o,{scale:e,low_quality:t=!1,title_height:n=_.NODE_TITLE_HEIGHT,box_size:i=10}){if(this.onDrawTitleBox){this.onDrawTitleBox(o,n,this.renderingSize,e);return}o.save(),o.fillStyle="#3b82f6",o.beginPath(),o.roundRect(6,-24.5,22,20,5),o.fill(),t||(o.translate(25,23),o.scale(-1.5,1.5),o.drawImage(An,0,-n,i,i)),o.restore()}serialize(){for(let o=0;o<this.widgets.length;o++){const e=this.widgets[o],t=this.inputs.find(n=>n.name===e.name);if(t){const n=this.subgraph.inputNode.slots.find(i=>i.name===t.name);if(n){const i=n.getConnectedWidgets();for(const s of i)s.value=e.value}}}return super.serialize()}clone(){const o=super.clone();return this.properties.proxyWidgets=this.properties.proxyWidgets,o}};function Dn(o){const e=o?.find(a=>a);if(!e)return null;let t=e,n=e,i=e,s=e;for(const a of o){if(!a)continue;const[r,l]=a.pos,[d,u]=a.size;l<t.pos[1]&&(t=a),r+d>n.pos[0]+n.size[0]&&(n=a),l+u>i.pos[1]+i.size[1]&&(i=a),r<s.pos[0]&&(s=a)}return{top:t,right:n,bottom:i,left:s}}h(Dn,"getBoundaryNodes");function Rw(o,e){const t=o?.length;if(!(t>1))return[];const n=e?0:1;let i=0,s=-1/0;for(const u of o){i+=u.size[n];const p=u.pos[n]+u.size[n];p>s&&(s=p)}const a=[...o].sort((u,p)=>u.pos[n]-p.pos[n]),r=a[0].pos[n],l=(s-r-i)/(t-1);let d=r;for(let u=0;u<t;u++){const p=a[u];p.pos[n]=d+l*u,d+=p.size[n]}return a.map(u=>({node:u,newPos:{x:u.pos[0],y:u.pos[1]}}))}h(Rw,"distributeNodes");function Wt(o,e,t){if(!o)return[];const n=t===void 0?Dn(o):{top:t,right:t,bottom:t,left:t};if(n===null)return[];const i=o.map(s=>{switch(e){case"right":return{node:s,newPos:{x:n.right.pos[0]+n.right.size[0]-s.size[0],y:s.pos[1]}};case"left":return{node:s,newPos:{x:n.left.pos[0],y:s.pos[1]}};case"top":return{node:s,newPos:{x:s.pos[0],y:n.top.pos[1]}};case"bottom":return{node:s,newPos:{x:s.pos[0],y:n.bottom.pos[1]+n.bottom.size[1]-s.size[1]}}}});for(const{node:s,newPos:a}of i)s.pos[0]=a.x,s.pos[1]=a.y;return i}h(Wt,"alignNodes");function Fw(o){return o===_.EVENT?_.EVENT_LINK_COLOR:_.CONNECTING_LINK_COLOR}h(Fw,"resolveConnectingLinkColor");var Gt={NE:"nesw-resize",SE:"nwse-resize",SW:"nesw-resize",NW:"nwse-resize"},zw=new X,Bw=[0,0],Vw=new X,$e=new X,Te=new X,ce=class L{static{h(this,"LGraphCanvas")}static DEFAULT_BACKGROUND_IMAGE="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=";static DEFAULT_EVENT_LINK_COLOR="#A86";static link_type_colors={"-1":L.DEFAULT_EVENT_LINK_COLOR,number:"#AAA",node:"#DCA"};static gradients={};static search_limit=-1;static node_colors={red:{color:"#322",bgcolor:"#533",groupcolor:"#A88"},brown:{color:"#332922",bgcolor:"#593930",groupcolor:"#b06634"},green:{color:"#232",bgcolor:"#353",groupcolor:"#8A8"},blue:{color:"#223",bgcolor:"#335",groupcolor:"#88A"},pale_blue:{color:"#2a363b",bgcolor:"#3f5159",groupcolor:"#3f789e"},cyan:{color:"#233",bgcolor:"#355",groupcolor:"#8AA"},purple:{color:"#323",bgcolor:"#535",groupcolor:"#a1309b"},yellow:{color:"#432",bgcolor:"#653",groupcolor:"#b58b2a"},black:{color:"#222",bgcolor:"#000",groupcolor:"#444"}};static _measureText;state={draggingItems:!1,draggingCanvas:!1,readOnly:!1,hoveringOver:te.Nothing,shouldSetCursor:!0,selectionChanged:!1};#e;get subgraph(){return this.#e}set subgraph(e){e!==this.#e&&(this.#e=e,e&&this.dispatch("litegraph:set-graph",{oldGraph:this.#e,newGraph:e}))}fpsInfoLocation;dispatch(e,t){const n=new CustomEvent(e,{detail:t,bubbles:!0});return this.canvas.dispatchEvent(n)}dispatchEvent(e,t){this.canvas.dispatchEvent(new CustomEvent(e,{detail:t}))}#t(){if(!this.state.shouldSetCursor)return;const e=te.Node|te.RerouteSlot|te.SubgraphIoNode|te.SubgraphIoSlot;let t="default";this.state.draggingCanvas?t="grabbing":this.state.readOnly?t="grab":this.pointer.resizeDirection?t=Gt[this.pointer.resizeDirection]??Gt.SE:this.state.hoveringOver&e?t="crosshair":this.state.hoveringOver&te.Reroute&&(t="grab"),this.canvas.style.cursor=t}_previously_dragging_canvas=null;get read_only(){return this.state.readOnly}set read_only(e){this.state.readOnly=e,this.#t()}get isDragging(){return this.state.draggingItems}set isDragging(e){this.state.draggingItems=e}get hoveringOver(){return this.state.hoveringOver}set hoveringOver(e){this.state.hoveringOver=e,this.#t()}get pointer_is_down(){return this.pointer.isDown}get pointer_is_double(){return this.pointer.isDouble}get dragging_canvas(){return this.state.draggingCanvas}set dragging_canvas(e){this.state.draggingCanvas=e,this.#t()}get title_text_font(){return`${_.NODE_TEXT_SIZE}px ${_.NODE_FONT}`}get inner_text_font(){return`normal ${_.NODE_SUBTEXT_SIZE}px ${_.NODE_FONT}`}#o=0;get maximumFps(){return this.#o>Number.EPSILON?this.#o/1e3:0}set maximumFps(e){this.#o=e>Number.EPSILON?1e3/e:0}get round_radius(){return _.ROUND_RADIUS}set round_radius(e){_.ROUND_RADIUS=e}_lowQualityZoomThreshold=0;_isLowQuality=!1;updateLowQualityThreshold(){if(this._min_font_size_for_lod===0){this._lowQualityZoomThreshold=0,this._isLowQuality=!1;return}const e=_.NODE_TEXT_SIZE,t=Math.sqrt(window.devicePixelRatio||1);this._lowQualityZoomThreshold=this._min_font_size_for_lod/(e*t),this._isLowQuality=this.ds.scale<this._lowQualityZoomThreshold}get low_quality(){return this._isLowQuality}options;background_image;ds;pointer;zoom_modify_alpha;zoom_speed;node_title_color;default_link_color;default_connection_color;default_connection_color_byType;default_connection_color_byTypeOff;colourGetter={getConnectedColor:h(e=>this.default_connection_color_byType[e]||this.default_connection_color.output_on,"getConnectedColor"),getDisconnectedColor:h(e=>this.default_connection_color_byTypeOff[e]||this.default_connection_color_byType[e]||this.default_connection_color.output_off,"getDisconnectedColor")};highquality_render;use_gradients;editor_alpha;pause_rendering;clear_background;clear_background_color;render_only_selected;show_info;allow_dragcanvas;allow_dragnodes;allow_interaction;multi_select;allow_searchbox;allow_reconnect_links;align_to_grid;drag_mode;dragging_rectangle;filter;set_canvas_dirty_on_mouse_event;always_render_background;render_shadows;render_canvas_border;render_connections_shadows;render_connections_border;render_curved_connections;render_connection_arrows;render_collapsed_slots;render_execution_order;render_link_tooltip;linkMarkerShape=re.Circle;links_render_mode;_min_font_size_for_lod=8;get min_font_size_for_lod(){return this._min_font_size_for_lod}set min_font_size_for_lod(e){this._min_font_size_for_lod!==e&&(this._min_font_size_for_lod=e,this.updateLowQualityThreshold())}mouse;graph_mouse;canvas_mouse;onSearchBox;onSearchBoxSelection;onMouse;onDrawBackground;onDrawForeground;connections_width;current_node;node_widget;over_link_center;last_mouse_position;visible_area;renderedPaths=new Set;visible_links=[];connecting_links;linkConnector=new Mw(e=>this.connecting_links=e);viewport;autoresize;static active_canvas;frame=0;last_draw_time=0;render_time=0;fps=0;selected_nodes={};selectedItems=new Set;resizingGroup=null;selected_group=null;visible_nodes=[];#n=new Set;node_over;node_capturing_input;highlighted_links={};#s=new Set;dirty_canvas=!0;dirty_bgcanvas=!0;dirty_nodes=new Map;dirty_area;node_in_panel;last_mouse=[0,0];last_mouseclick=0;graph;get _graph(){if(!this.graph)throw new N;return this.graph}canvas;bgcanvas;ctx;_events_binded;bgctx;is_rendering;block_click;last_click_position;resizing_node;selected_group_resizing;last_mouse_dragging;onMouseDown;_highlight_pos;_highlight_input;node_panel;options_panel;_bg_img;_pattern;_pattern_img;bg_tint;prompt_box;search_box;SELECTED_NODE;NODEPANEL_IS_OPEN;#i;#d=!1;linkRenderer=null;dragZoomEnabled=!1;#a=null;liveSelection=!1;static active_node;onClear;onNodeMoved;onSelectionChange;onDrawLinkTooltip;onDrawOverlay;onRenderBackground;onNodeDblClicked;onShowNodePanel;onNodeSelected;onNodeDeselected;onRender;constructor(e,t,n){n||={},this.options=n,this.background_image=L.DEFAULT_BACKGROUND_IMAGE,this.ds=new tn(e),this.pointer=new ms(e),this.ds.onChanged=(i,s)=>{this._lowQualityZoomThreshold>0&&(this._isLowQuality=i<this._lowQualityZoomThreshold)},t&&(this.linkRenderer=new yo(!1)),this.linkConnector.events.addEventListener("link-created",()=>this.#r()),this.linkConnector.events.addEventListener("reset",()=>{this.connecting_links=null,this.dirty_bgcanvas=!0}),this.linkConnector.events.addEventListener("dropped-on-canvas",i=>{if(!this.connecting_links)return;const s=i.detail;this.emitEvent({subType:"empty-release",originalEvent:s,linkReleaseContext:{links:this.connecting_links}});const a=this.linkConnector.renderLinks[0];if(_.release_link_on_empty_shows_menu){const r=this.linkConnector.state.connectingTo==="input"?{node_from:a.node,slot_from:a.fromSlot,type_filter_in:a.fromSlot.type}:{node_to:a.node,slot_to:a.fromSlot,type_filter_out:a.fromSlot.type},l=a.fromReroute?.id;"shiftKey"in s&&s.shiftKey?this.allow_searchbox&&this.showSearchBox(s,r):this.linkConnector.state.connectingTo==="input"?this.showConnectionMenu({nodeFrom:a.node,slotFrom:a.fromSlot,e:s,afterRerouteId:l}):this.showConnectionMenu({nodeTo:a.node,slotTo:a.fromSlot,e:s,afterRerouteId:l})}}),this.zoom_modify_alpha=!0,this.zoom_speed=1.1,this.node_title_color=_.NODE_TITLE_COLOR,this.default_link_color=_.LINK_COLOR,this.default_connection_color={input_off:"#778",input_on:"#7F7",output_off:"#778",output_on:"#7F7"},this.default_connection_color_byType={},this.default_connection_color_byTypeOff={},this.highquality_render=!0,this.use_gradients=!1,this.editor_alpha=1,this.pause_rendering=!1,this.clear_background=!0,this.clear_background_color="#222",this.render_only_selected=!0,this.show_info=!0,this.allow_dragcanvas=!0,this.allow_dragnodes=!0,this.allow_interaction=!0,this.multi_select=!1,this.allow_searchbox=!0,this.allow_reconnect_links=!0,this.align_to_grid=!1,this.drag_mode=!1,this.dragging_rectangle=null,this.filter=null,this.set_canvas_dirty_on_mouse_event=!0,this.always_render_background=!1,this.render_shadows=!0,this.render_canvas_border=!0,this.render_connections_shadows=!1,this.render_connections_border=!0,this.render_curved_connections=!1,this.render_connection_arrows=!1,this.render_collapsed_slots=!0,this.render_execution_order=!1,this.render_link_tooltip=!0,this.links_render_mode=ie.SPLINE_LINK,this.mouse=[0,0],this.graph_mouse=[0,0],this.canvas_mouse=this.graph_mouse,this.connections_width=3,this.current_node=null,this.node_widget=null,this.last_mouse_position=[0,0],this.visible_area=this.ds.visible_area,this.connecting_links=null,this.viewport=n.viewport,this.graph=t,t?.attachCanvas(this),this.canvas=void 0,this.bgcanvas=void 0,this.ctx=void 0,this.setCanvas(e,n.skip_events),this.clear(),L._measureText=(i,s=this.inner_text_font)=>{const{ctx:a}=this,{font:r}=a;try{return a.font=s,a.measureText(i).width}finally{a.font=r}},n.skip_render||this.startRendering(),this.autoresize=n.autoresize??!1,this.updateLowQualityThreshold()}static onGroupAdd(e,t,n){const i=L.active_canvas,s=new _.LGraphGroup;if(s.pos=i.convertEventToCanvasOffset(n),!i.graph)throw new N;i.graph.add(s)}static getBoundaryNodes(e){return Dn(Array.isArray(e)?e:Object.values(e))??{top:null,right:null,bottom:null,left:null}}static alignNodes(e,t,n){const i=Wt(Object.values(e),t,n);L.active_canvas.repositionNodesVueMode(i),L.active_canvas.setDirty(!0,!0)}static onNodeAlign(e,t,n,i,s){new _.ContextMenu(["Top","Bottom","Left","Right"],{event:n,callback:a,parentMenu:i});function a(r){const l=Wt(Object.values(L.active_canvas.selected_nodes),r.toLowerCase(),s);L.active_canvas.repositionNodesVueMode(l),L.active_canvas.setDirty(!0,!0)}h(a,"inner_clicked")}static onGroupAlign(e,t,n,i){new _.ContextMenu(["Top","Bottom","Left","Right"],{event:n,callback:s,parentMenu:i});function s(a){const r=Wt(Object.values(L.active_canvas.selected_nodes),a.toLowerCase());L.active_canvas.repositionNodesVueMode(r),L.active_canvas.setDirty(!0,!0)}h(s,"inner_clicked")}static createDistributeMenu(e,t,n,i){new _.ContextMenu(["Vertically","Horizontally"],{event:n,callback:s,parentMenu:i});function s(a){const r=L.active_canvas,l=Rw(Object.values(r.selected_nodes),a==="Horizontally");r.repositionNodesVueMode(l),r.setDirty(!0,!0)}h(s,"inner_clicked")}static onMenuAdd(e,t,n,i,s){const a=L.active_canvas,{graph:r}=a;if(!r)return;return l("",i),!1;function l(d,u){if(!r)return;const p=_.getNodeTypesCategories(a.filter||r.filter).filter(f=>f.startsWith(d)),m=[];for(const f of p){if(!f)continue;const y=new RegExp(`^(${d})`),b=f.replace(y,"").split("/",1)[0],v=d===""?`${b}/`:`${d}${b}/`;let k=b;k.includes("::")&&(k=k.split("::",2)[1]),m.findIndex(w=>w.value===v)===-1&&m.push({value:v,content:k,has_submenu:!0,callback:h(function(w,S,E,C){l(w.value,C)},"callback")})}const g=_.getNodeTypesInCategory(d.slice(0,-1),a.filter||r.filter);for(const f of g){if(f.skip_list)continue;const y={value:f.type,content:f.title,has_submenu:!1,callback:h(function(b,v,k,w){if(!a.graph)throw new N;const S=w.getFirstEvent();a.graph.beforeChange();const E=_.createNode(b.value);if(E){if(!S)throw new TypeError("Context menu event was null. This should not occur in normal usage.");E.pos=a.convertEventToCanvasOffset(S),a.graph.add(E)}else console.warn("Failed to create node of type:",b.value);s?.(E),a.graph.afterChange()},"callback")};m.push(y)}new _.ContextMenu(m,{event:n,parentMenu:u})}h(l,"inner_onMenuAdded")}static onMenuCollapseAll(){}static onMenuNodeEdit(){}static showMenuNodeOptionalOutputs(e,t,n,i,s){if(!s)return;const a=L.active_canvas;let r=[];_.do_add_triggers_slots&&s.findOutputSlot("onExecuted")==-1&&r.push({content:"On Executed",value:["onExecuted",_.EVENT,{nameLocked:!0}],className:"event"});const l=s.onMenuNodeOutputs?.(r);if(l&&(r=l),!r.length)return;new _.ContextMenu(r,{event:n,callback:d,parentMenu:i,node:s});function d(u,p,m,g){if(!s||!u||typeof u=="string"||(u.callback&&u.callback.call(this,s,u,m,g),!u.value))return;const f=u.value[1];if(f&&(typeof f=="object"||Array.isArray(f))){const b=[];for(const v in f)b.push({content:v,value:f[v]});return new _.ContextMenu(b,{event:m,callback:d,parentMenu:i,node:s}),!1}const{graph:y}=s;if(!y)throw new N;y.beforeChange(),s.addOutput(u.value[0],u.value[1],u.value[2]),s.onNodeOutputAdd?.(u.value),a.setDirty(!0,!0),y.afterChange()}return h(d,"inner_clicked"),!1}static onShowMenuNodeProperties(e,t,n,i,s){if(!s||!s.properties)return;const a=L.active_canvas,r=[];for(const d in s.properties){e=s.properties[d]!==void 0?s.properties[d]:" ",typeof e=="object"&&(e=JSON.stringify(e));const u=s.getPropertyInfo(d);(u.type=="enum"||u.type=="combo")&&(e=L.getPropertyPrintableValue(e,u.values)),e=L.decodeHTML($t(e)),r.push({content:`<span class='property_name'>${u.label||d}</span><span class='property_value'>${e}</span>`,value:d})}if(!r.length)return;new _.ContextMenu(r,{event:n,callback:l,parentMenu:i,node:s});function l(d){if(!s||typeof d=="string"||!d?.value)return;const u=this.root.getBoundingClientRect();a.showEditPropertyValue(s,d.value,{position:[u.left,u.top]})}return h(l,"inner_clicked"),!1}static decodeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}static onMenuResizeNode(e,t,n,i,s){if(!s)return;const a=h(function(l){l.setSize(l.computeSize())},"fApplyMultiNode"),r=L.active_canvas;if(!r.selected_nodes||Object.keys(r.selected_nodes).length<=1)a(s);else for(const l in r.selected_nodes)a(r.selected_nodes[l]);r.setDirty(!0,!0)}static onShowPropertyEditor(e,t,n,i,s){const a=e.property||"title",r=s[a],l=document.createElement("span");l.className="name",l.textContent=a;const d=document.createElement("input");Object.assign(d,{type:"text",className:"value",autofocus:!0});const u=document.createElement("button");u.textContent="OK";const p=Object.assign(document.createElement("div"),{is_modified:!1,className:"graphdialog",close:h(()=>p.remove(),"close")});p.append(l,d,u),d.value=String(r),d.addEventListener("blur",function(){this.focus()}),d.addEventListener("keydown",S=>{if(p.is_modified=!0,S.key=="Escape")p.close();else if(S.key=="Enter")k();else if(!S.target||!("localName"in S.target)||S.target.localName!="textarea")return;S.preventDefault(),S.stopPropagation()});const m=L.active_canvas,g=m.canvas,f=g.getBoundingClientRect(),y=f?-20-f.left:-20,b=f?-20-f.top:-20;if(n?(p.style.left=`${n.clientX+y}px`,p.style.top=`${n.clientY+b}px`):(p.style.left=`${g.width*.5+y}px`,p.style.top=`${g.height*.5+b}px`),u.addEventListener("click",k),g.parentNode==null)throw new TypeError("canvasEl.parentNode was null");g.parentNode.append(p),d.focus();let v;p.addEventListener("mouseleave",function(){_.dialog_close_on_mouse_leave&&!p.is_modified&&_.dialog_close_on_mouse_leave&&(v=setTimeout(p.close,_.dialog_close_on_mouse_leave_delay))}),p.addEventListener("mouseenter",function(){_.dialog_close_on_mouse_leave&&v&&clearTimeout(v)});function k(){d&&w(d.value)}h(k,"inner");function w(S){e.type=="Number"?S=Number(S):e.type=="Boolean"&&(S=!!S),s[a]=S,p.remove(),m.setDirty(!0,!0)}h(w,"setValue")}static getPropertyPrintableValue(e,t){if(!t||Array.isArray(t))return String(e);if(typeof t=="object"){let n="";for(const i in t)if(t[i]==e){n=i;break}return`${String(e)} (${n})`}}static onMenuNodeCollapse(e,t,n,i,s){if(!s.graph)throw new N;s.graph.beforeChange();const a=h(function(l){l.collapse()},"fApplyMultiNode"),r=L.active_canvas;if(!r.selected_nodes||Object.keys(r.selected_nodes).length<=1)a(s);else for(const l in r.selected_nodes)a(r.selected_nodes[l]);s.graph.afterChange()}static onMenuToggleAdvanced(e,t,n,i,s){if(!s.graph)throw new N;s.graph.beforeChange();const a=h(function(l){l.toggleAdvanced()},"fApplyMultiNode"),r=L.active_canvas;if(!r.selected_nodes||Object.keys(r.selected_nodes).length<=1)a(s);else for(const l in r.selected_nodes)a(r.selected_nodes[l]);s.graph.afterChange()}static onMenuNodeMode(e,t,n,i,s){new _.ContextMenu(_.NODE_MODES,{event:n,callback:a,parentMenu:i,node:s});function a(r){if(!s)return;const l=Object.values(_.NODE_MODES).indexOf(r),d=h(function(p){l!==-1&&_.NODE_MODES[l]?p.changeMode(l):(console.warn(`unexpected mode: ${r}`),p.changeMode(H.ALWAYS))},"fApplyMultiNode"),u=L.active_canvas;if(!u.selected_nodes||Object.keys(u.selected_nodes).length<=1)d(s);else for(const p in u.selected_nodes)d(u.selected_nodes[p])}return h(a,"inner_clicked"),!1}static onMenuNodeColors(e,t,n,i,s){if(!s)throw"no node for color";const a=[];a.push({value:null,content:"<span style='display: block; padding-left: 4px;'>No color</span>"});for(const l in L.node_colors){const d=L.node_colors[l];e={value:l,content:`<span style='display: block; color: #999; padding-left: 4px; border-left: 8px solid ${d.color}; background-color:${d.bgcolor}'>${l}</span>`},a.push(e)}new _.ContextMenu(a,{event:n,callback:r,parentMenu:i,node:s});function r(l){if(!s)return;const d=h(function(p){const m=l.value?L.node_colors[l.value]:null;p.setColorOption(m)},"fApplyColor"),u=L.active_canvas;if(!u.selected_nodes||Object.keys(u.selected_nodes).length<=1)d(s);else for(const p in u.selected_nodes)d(u.selected_nodes[p]);u.setDirty(!0,!0)}return h(r,"inner_clicked"),!1}static onMenuNodeShapes(e,t,n,i,s){if(!s)throw"no node passed";new _.ContextMenu(_.VALID_SHAPES,{event:n,callback:a,parentMenu:i,node:s});function a(r){if(!s)return;if(!s.graph)throw new N;s.graph.beforeChange();const l=h(function(u){u.shape=r},"fApplyMultiNode"),d=L.active_canvas;if(!d.selected_nodes||Object.keys(d.selected_nodes).length<=1)l(s);else for(const u in d.selected_nodes)l(d.selected_nodes[u]);s.graph.afterChange(),d.setDirty(!0)}return h(a,"inner_clicked"),!1}static onMenuNodeRemove(){L.active_canvas.deleteSelected()}static onMenuNodeClone(e,t,n,i,s){const a=L.active_canvas,r=a.selectedItems.size?[...a.selectedItems]:[s];r.length&&L.cloneNodes(r)}static cloneNodes(e){const t=L.active_canvas;let n=1/0,i=1/0;for(const s of e){if(s.pos==null)throw new TypeError("Invalid node encountered on clone. `pos` was null.");n=Math.min(n,s.pos[0]),i=Math.min(i,s.pos[1])}return t._deserializeItems(t._serializeItems(e),{position:[n+5,i+5]})}clear(){this.frame=0,this.last_draw_time=0,this.render_time=0,this.fps=0,this.dragging_rectangle=null,this.selected_nodes={},this.selected_group=null,this.selectedItems.clear(),this.state.selectionChanged=!0,this.onSelectionChange?.(this.selected_nodes),this.visible_nodes=[],this.node_over=void 0,this.node_capturing_input=null,this.connecting_links=null,this.highlighted_links={},this.dragging_canvas=!1,this.#r(),this.dirty_area=null,this.node_in_panel=null,this.node_widget=null,this.last_mouse=[0,0],this.last_mouseclick=0,this.pointer.reset(),this.visible_area.set([0,0,0,0]),this.onClear?.()}setGraph(e){const{graph:t}=this;e!==t&&(this.clear(),e.attachCanvas(this),this.linkRenderer=new yo(!1),this.dispatch("litegraph:set-graph",{newGraph:e,oldGraph:t}),this.#r())}openSubgraph(e,t){const{graph:n}=this;if(!n)throw new N;const i={bubbles:!0,detail:{subgraph:e,closingGraph:n,fromNode:t},cancelable:!0};this.canvas.dispatchEvent(new CustomEvent("subgraph-opening",i))&&(this.clear(),this.subgraph=e,this.setGraph(e),this.canvas.dispatchEvent(new CustomEvent("subgraph-opened",i)))}getCurrentGraph(){return this.graph}#c(e){if(typeof e=="string"){const t=document.getElementById(e);if(!(t instanceof HTMLCanvasElement))throw"Error validating LiteGraph canvas: Canvas element not found";return t}return e}setCanvas(e,t){const n=this.#c(e);if(n===this.canvas||(!n&&this.canvas&&!t&&this.unbindEvents(),this.canvas=n,this.ds.element=n,this.pointer.element=n,!n))return;n.className+=" lgraphcanvas",n.data=this,this.bgcanvas=document.createElement("canvas"),this.bgcanvas.width=this.canvas.width,this.bgcanvas.height=this.canvas.height;const i=n.getContext?.("2d");if(i==null)throw n.localName!="canvas"?`Element supplied for LGraphCanvas must be a <canvas> element, you passed a ${n.localName}`:"This browser doesn't support Canvas";this.ctx=i,t||this.bindEvents()}_doNothing(e){return e.preventDefault(),!1}_doReturnTrue(e){return e.preventDefault(),!0}bindEvents(){if(this._events_binded){console.warn("LGraphCanvas: events already bound");return}const{canvas:e}=this,{document:t}=this.getCanvasWindow();this._mousedown_callback=this.processMouseDown.bind(this),this._mousewheel_callback=this.processMouseWheel.bind(this),this._mousemove_callback=this.processMouseMove.bind(this),this._mouseup_callback=this.processMouseUp.bind(this),this._mouseout_callback=this.processMouseOut.bind(this),this._mousecancel_callback=this.processMouseCancel.bind(this),e.addEventListener("pointerdown",this._mousedown_callback,!0),e.addEventListener("wheel",this._mousewheel_callback,!1),e.addEventListener("pointerup",this._mouseup_callback,!0),e.addEventListener("pointermove",this._mousemove_callback),e.addEventListener("pointerout",this._mouseout_callback),e.addEventListener("pointercancel",this._mousecancel_callback,!0),e.addEventListener("contextmenu",this._doNothing),this._key_callback=this.processKey.bind(this),e.addEventListener("keydown",this._key_callback,!0),t.addEventListener("keyup",this._key_callback,!0),e.addEventListener("dragover",this._doNothing,!1),e.addEventListener("dragend",this._doNothing,!1),e.addEventListener("dragenter",this._doReturnTrue,!1),this._events_binded=!0}unbindEvents(){if(!this._events_binded){console.warn("LGraphCanvas: no events bound");return}const{document:e}=this.getCanvasWindow(),{canvas:t}=this;t.removeEventListener("pointercancel",this._mousecancel_callback),t.removeEventListener("pointerout",this._mouseout_callback),t.removeEventListener("pointermove",this._mousemove_callback),t.removeEventListener("pointerup",this._mouseup_callback),t.removeEventListener("pointerdown",this._mousedown_callback),t.removeEventListener("wheel",this._mousewheel_callback),t.removeEventListener("keydown",this._key_callback),e.removeEventListener("keyup",this._key_callback),t.removeEventListener("contextmenu",this._doNothing),t.removeEventListener("dragenter",this._doReturnTrue),this._mousedown_callback=void 0,this._mousewheel_callback=void 0,this._key_callback=void 0,this._events_binded=!1}setDirty(e,t){e&&(this.dirty_canvas=!0),t&&(this.dirty_bgcanvas=!0)}#r(){this.dirty_canvas=!0,this.dirty_bgcanvas=!0}#l(){const{graph:e,linkConnector:t,pointer:n}=this;if(!e)throw new N;n.onDragEnd=i=>t.dropLinks(e,i),n.finally=()=>this.linkConnector.reset(!0)}getCanvasWindow(){if(!this.canvas)return window;const e=this.canvas.ownerDocument;return e.defaultView||e.parentWindow}startRendering(){if(this.is_rendering)return;this.is_rendering=!0,e.call(this);function e(){this.pause_rendering||this.draw();const t=this.getCanvasWindow();if(this.is_rendering)if(this.#o>0){const n=this.#o-(_.getTime()-this.last_draw_time);setTimeout(e.bind(this),Math.max(1,n))}else t.requestAnimationFrame(e.bind(this))}h(e,"renderFrame")}stopRendering(){this.is_rendering=!1}blockClick(){this.block_click=!0,this.last_mouseclick=0}getWidgetAtCursor(e){return e??=this.node_over,e?.getWidgetOnPos(this.graph_mouse[0],this.graph_mouse[1],!0)}updateMouseOverNodes(e,t){if(!this.graph)throw new N;const{pointer:n}=this,i=this.graph._nodes;for(const s of i)s.mouseOver&&e!=s&&(n.eDown||(n.resizeDirection=void 0),s.mouseOver=void 0,this._highlight_input=void 0,this._highlight_pos=void 0,this.linkConnector.overWidget=void 0,s.lostFocusAt=_.getTime(),this.node_over?.onMouseLeave?.(t),this.node_over=void 0,this.dirty_canvas=!0)}processMouseDown(e){if(this.dragZoomEnabled&&e.ctrlKey&&e.shiftKey&&!e.altKey&&e.buttons){this.#a={pos:[e.x,e.y],scale:this.ds.scale,readOnly:this.read_only},this.read_only=!0;return}const{graph:t,pointer:n}=this;if(this.adjustMouseEvent(e),e.isPrimary&&n.down(e),this.set_canvas_dirty_on_mouse_event&&(this.dirty_canvas=!0),!t)return;const i=this.getCanvasWindow();L.active_canvas=this;const s=e.clientX,a=e.clientY;if(this.ds.viewport=this.viewport,!(!this.viewport||yt(s,a,this.viewport)))return;const r=t.getNodeOnPos(e.canvasX,e.canvasY,this.visible_nodes)??void 0;if(this.mouse[0]=s,this.mouse[1]=a,this.graph_mouse[0]=e.canvasX,this.graph_mouse[1]=e.canvasY,this.last_click_position=[this.mouse[0],this.mouse[1]],n.isDouble=n.isDown&&e.isPrimary,n.isDown=!0,this.canvas.focus(),_.closeAllContextMenus(i),this.onMouse?.(e)!=!0){if(e.button===0&&!n.isDouble)this.#f(e,r);else if(e.button===1)this.#_(e,r);else if((e.button===2||n.isDouble)&&this.allow_interaction&&!this.read_only){const{linkConnector:l,subgraph:d}=this;if(d?.inputNode.containsPoint(this.graph_mouse))this.processSelect(d.inputNode,e,!0),d.inputNode.onPointerDown(e,n,l);else if(d?.outputNode.containsPoint(this.graph_mouse))this.processSelect(d.outputNode,e,!0),d.outputNode.onPointerDown(e,n,l);else{if(r)this.processSelect(r,e,!0);else if(this.links_render_mode!==ie.HIDDEN_LINK){const u=D.queryRerouteAtPoint({x:e.canvasX,y:e.canvasY});let p;u?p=t.getReroute(u.id):p=t.getRerouteOnPos(e.canvasX,e.canvasY,this.#s),p&&(e.altKey?n.onClick=m=>{m.altKey&&(p.selected&&(this.deselect(p),this.onSelectionChange?.(this.selected_nodes)),p.remove())}:this.processSelect(p,e,!0))}n.onClick??=()=>this.processContextMenu(r,e)}}this.last_mouse=[s,a],this.last_mouseclick=_.getTime(),this.last_mouse_dragging=!0,t.change(),(!i.document.activeElement||i.document.activeElement.nodeName.toLowerCase()!="input"&&i.document.activeElement.nodeName.toLowerCase()!="textarea")&&e.preventDefault(),e.stopPropagation(),this.onMouseDown?.(e)}}#u(e,t){const n=this.subgraph?.getIoNodeOnPos(e,t);if(n)return n;for(const i of this.#s)if(i.containsPoint([e,t]))return i;return this.graph?.getGroupTitlebarOnPos(e,t)}#f(e,t){const{pointer:n,graph:i,linkConnector:s,subgraph:a}=this;if(!i)throw new N;const r=e.canvasX,l=e.canvasY,d=e.ctrlKey||e.metaKey;if(d&&!e.altKey&&_.leftMouseClickBehavior==="panning"){this.#p(e,n,t);return}if(this.read_only){n.finally=()=>this.dragging_canvas=!1,this.dragging_canvas=!0;return}if(!_.vueNodesMode&&_.alt_drag_do_clone_nodes&&e.altKey&&!e.ctrlKey&&t&&this.allow_interaction){const u=this._deserializeItems(this._serializeItems([t]),{position:t.pos})?.created[0];if(!u)return;u.pos[0]+=5,u.pos[1]+=5,this.allow_dragnodes&&(n.onDragStart=p=>{this.#h(u,p)},n.onDragEnd=p=>this.#g(p));return}if(t&&(this.allow_interaction||t.flags.allow_interaction))this.#m(e,d,t);else{if(a){let b=function(v,k){return k.containsPoint([r,l])?(k.onPointerDown(e,n,s),n.onClick??=()=>v.processSelect(k,e),n.onDragStart??=()=>v.#h(k,n,!0),n.onDragEnd??=w=>v.#g(w),!0):!1};h(b,"processSubgraphIONode");const{inputNode:f,outputNode:y}=a;if(b(this,f)||b(this,y))return}if(this.links_render_mode!==ie.HIDDEN_LINK){const f=D.queryRerouteAtPoint({x:r,y:l});let y;f&&(y=i.getReroute(f.id));for(const b of this.#s){const v=y===b||b.containsPoint([r,l]);if(!(!b.isSlotHovered&&!v)){v&&(n.onClick=()=>this.processSelect(b,e),e.shiftKey||(n.onDragStart=k=>this.#h(b,k,!0),n.onDragEnd=k=>this.#g(k))),(b.isOutputHovered||v&&e.shiftKey)&&(s.dragFromReroute(i,b),this.#l()),b.isInputHovered&&(s.dragFromRerouteToOutput(i,b),this.#l()),b.hideSlots(),this.dirty_bgcanvas=!0;return}}}const{lineWidth:u}=this.ctx;this.ctx.lineWidth=this.connections_width+7;const p=Math.max(window?.devicePixelRatio??1,1),m=D.queryLinkSegmentAtPoint({x:r,y:l},this.ctx);for(const f of this.renderedPaths){const y=f._pos;if(!y)continue;let b=m&&f.id===(f instanceof J?m.rerouteId:m.linkId);if(!b&&f.path&&(b=this.ctx.isPointInStroke(f.path,r*p,l*p)),(e.shiftKey||e.altKey)&&b){if(this.ctx.lineWidth=u,e.shiftKey&&!e.altKey){s.dragFromLinkSegment(i,f),this.#l();return}else if(e.altKey&&!e.shiftKey){const v=i.createReroute([r,l],f);n.onDragStart=k=>this.#h(v,k),n.onDragEnd=k=>this.#g(k);return}}else if(this.linkMarkerShape!==re.None&&G(r,l,y[0]-4,y[1]-4,8,8)){this.ctx.lineWidth=u,n.onClick=()=>this.showLinkMenu(f,e),n.onDragStart=()=>this.dragging_canvas=!0,n.finally=()=>this.dragging_canvas=!1,this.over_link_center=void 0;return}}this.ctx.lineWidth=u;const g=i.getGroupOnPos(r,l);if(this.selected_group=g??null,g){if(g.isInResize(r,l)){const f=g.boundingRect,y=r-(f[0]+f[2]),b=l-(f[1]+f[3]);n.onDragStart=()=>this.resizingGroup=g,n.onDrag=v=>{if(this.read_only)return;const k=[v.canvasX-g.pos[0]-y,v.canvasY-g.pos[1]-b];this.#i&&xe(k,this.#i),g.resize(k[0],k[1])&&(this.dirty_bgcanvas=!0)},n.finally=()=>this.resizingGroup=null}else{const f=(g.font_size||_.DEFAULT_GROUP_FONT_SIZE)*1.4;G(r,l,g.pos[0],g.pos[1],g.size[0],f)&&(n.onClick=()=>this.processSelect(g,e),n.onDragStart=y=>{g.recomputeInsideNodes(),this.#h(g,y,!0)},n.onDragEnd=y=>this.#g(y))}n.onDoubleClick=()=>{this.emitEvent({subType:"group-double-click",originalEvent:e,group:g})}}else n.onDoubleClick=()=>{this.allow_searchbox&&(this.showSearchBox(e),e.preventDefault()),this.emitEvent({subType:"empty-double-click",originalEvent:e})}}!n.onDragStart&&!n.onClick&&!n.onDrag&&this.allow_dragcanvas&&(_.leftMouseClickBehavior==="panning"||this.read_only?(n.onClick=()=>this.processSelect(null,e),n.finally=()=>this.dragging_canvas=!1,this.dragging_canvas=!0):this.#p(e,n))}#p(e,t,n){const i=[0,0,0,0];if(i[0]=e.canvasX,i[1]=e.canvasY,i[2]=1,i[3]=1,t.onClick=s=>{const a=n??this.#u(s.canvasX,s.canvasY);this.processSelect(a,s)},t.onDragStart=()=>this.dragging_rectangle=i,this.liveSelection){const s=new Set(this.selectedItems);t.onDrag=a=>this.handleLiveSelect(a,i,s),t.onDragEnd=()=>this.finalizeLiveSelect()}else t.onDragEnd=s=>this.#C(s,i);t.finally=()=>this.dragging_rectangle=null}#m(e,t,n){if(_.vueNodesMode)return;const{pointer:i,graph:s,linkConnector:a}=this;if(!s)throw new N;const r=e.canvasX,l=e.canvasY;i.onClick=()=>this.processSelect(n,e),n.flags.pinned||this.bringToFront(n);const d=n.isPointInCollapse(r,l);if(d)i.onClick=()=>{n.collapse(),this.setDirty(!0,!0)};else if(!n.flags.collapsed){let f=function(y,b){return[...y.links??[],...y._floatingLinks??new Set].some(v=>typeof v=="number"&&b.getLink(v)!==void 0)};h(f,"hasRelevantOutputLinks");const{inputs:m,outputs:g}=n;if(g)for(const[y,b]of g.entries()){const v=n.getOutputPos(y);if(G(r,l,v[0]-15,v[1]-10,30,20)){if(e.shiftKey&&f(b,s)){a.moveOutputLink(s,b),this.#l();return}a.dragNewFromOutput(s,n,b),this.#l(),_.shift_click_do_break_link_from?e.shiftKey&&n.disconnectOutput(y):_.ctrl_alt_click_do_break_link&&t&&e.altKey&&!e.shiftKey&&n.disconnectOutput(y),i.onDoubleClick=()=>n.onOutputDblClick?.(y,e),i.onClick=()=>n.onOutputClick?.(y,e);return}}if(m)for(const[y,b]of m.entries()){const v=n.getInputPos(y);if(b instanceof Be?yt(r,l,b.boundingRect):G(r,l,v[0]-15,v[1]-10,30,20)){i.onDoubleClick=()=>n.onInputDblClick?.(y,e),i.onClick=()=>n.onInputClick?.(y,e);const k=_.ctrl_alt_click_do_break_link&&t&&e.altKey&&!e.shiftKey;(b.link!==null||b._floatingLinks?.size)&&(k||_.click_do_break_link_to?n.disconnectInput(y,!0):(e.shiftKey||this.allow_reconnect_links)&&a.moveInputLink(s,b)),a.isConnecting||a.dragNewFromInput(s,n,b),this.#l(),this.dirty_bgcanvas=!0;return}}}const u=[r-n.pos[0],l-n.pos[1]],p=n.getWidgetOnPos(r,l);if(p)this.processWidgetClick(e,n,p),this.node_widget=[n,p];else{if(i.onDoubleClick=()=>{u[1]<0&&!d?n.onNodeTitleDblClick?.(e,u,this):n instanceof gt&&this.openSubgraph(n.subgraph,n),n.onDblClick?.(e,u,this),this.emitEvent({subType:"node-double-click",originalEvent:e,node:n}),this.processNodeDblClicked(n)},n.title_buttons?.length&&!n.flags.collapsed){const m=u[0],g=u[1];for(let f=0;f<n.title_buttons.length;f++){const y=n.title_buttons[f];if(y.visible&&y.isPointInside(m,g)){n.onTitleButtonClick(y,this),i.onClick=()=>{};return}}}if(n.onMouseDown?.(e,u,this)){i.onClick=()=>{};return}if(!this.allow_dragnodes)return;if(!n.flags.collapsed){const m=n.findResizeDirection(r,l);if(m){i.resizeDirection=m;const g=new X(n.pos[0],n.pos[1],n.size[0],n.size[1]);i.onDragStart=()=>{s.beforeChange(),this.resizing_node=n},i.onDrag=f=>{if(this.read_only)return;const y=f.canvasX-r,b=f.canvasY-l,v=new X(g.x,g.y,g.width,g.height);switch(m){case"NE":v.y=g.y+b,v.width=g.width+y,v.height=g.height-b;break;case"SE":v.width=g.width+y,v.height=g.height+b;break;case"SW":v.x=g.x+y,v.width=g.width-y,v.height=g.height+b;break;case"NW":v.x=g.x+y,v.y=g.y+b,v.width=g.width-y,v.height=g.height-b;break}if(this.#i){if(m.includes("N")||m.includes("W")){const w=v.x,S=v.y;xe(v.pos,this.#i),m.includes("N")&&(v.height+=S-v.y),m.includes("W")&&(v.width+=w-v.x)}xe(v.size,this.#i)}const k=n.computeSize();v.width<k[0]&&(m.includes("W")&&(v.x=g.x+g.width-k[0]),v.width=k[0]),v.height<k[1]&&(m.includes("N")&&(v.y=g.y+g.height-k[1]),v.height=k[1]),n.pos=v.pos,n.setSize(v.size),this.#r()},i.onDragEnd=()=>{this.#r(),s.afterChange(n)},i.finally=()=>{this.resizing_node=null,i.resizeDirection=void 0},this.canvas.style.cursor=Gt[m];return}}i.onDragStart=m=>this.#h(n,m,!0),i.onDragEnd=m=>this.#g(m)}this.dirty_canvas=!0}processWidgetClick(e,t,n,i=this.pointer){if(typeof n.onPointerDown=="function"&&n.onPointerDown(i,t,this))return;const s=n.value,a=this.graph_mouse,r=a[0]-t.pos[0],l=a[1]-t.pos[1],d=Ct(n,t,!1);if(d)i.onClick=()=>d.onClick({e,node:t,canvas:this}),i.onDrag=u=>d.onDrag?.({e:u,node:t,canvas:this});else if(n.mouse){const u=n.mouse(e,[r,l],t);u!=null&&(this.dirty_canvas=u)}if(s!=n.value){if(t.onWidgetChanged?.(n.name,n.value,s,n),!t.graph)throw new N;t.graph._version++}i.finally=()=>{if(n.mouse){const{eUp:u}=i;if(!u)return;const{canvasX:p,canvasY:m}=u;n.mouse(u,[p-t.pos[0],m-t.pos[1]],t)}this.node_widget=null}}#_(e,t){const{pointer:n}=this;if(_.middle_click_slot_add_default_node&&t&&this.allow_interaction&&!this.read_only&&!this.connecting_links&&!t.flags.collapsed){let i=!1,s=!1,a=!1;const{inputs:r,outputs:l}=t;if(l)for(const[d,u]of l.entries()){const p=t.getOutputPos(d);if(G(e.canvasX,e.canvasY,p[0]-15,p[1]-10,30,20)){i=u,s=d,a=!0;break}}if(r)for(const[d,u]of r.entries()){const p=t.getInputPos(d);if(G(e.canvasX,e.canvasY,p[0]-15,p[1]-10,30,20)){i=u,s=d,a=!1;break}}if(i&&s!==!1){const d=.5-(s+1)/(a?l.length:r.length),u=t.getBounding(),p=[a?u[0]+u[2]:u[0],e.canvasY-80];n.onClick=()=>this.createDefaultNodeForSlot({nodeFrom:a?t:null,slotFrom:a?s:null,nodeTo:a?null:t,slotTo:a?null:s,position:p,nodeType:"AUTO",posAdd:[a?30:-30,-d*130],posSizeFix:[a?0:-1,0]})}}this.allow_dragcanvas&&(n.onDragStart=()=>this.dragging_canvas=!0,n.finally=()=>this.dragging_canvas=!1)}#v(e){if(!e.buttons){this.#b();return}const t=this.#a;if(!t)throw new TypeError("Drag-zoom state object was null");if(!this.graph)throw new N;const n=e.y-t.pos[1],i=t.scale-n/100;this.ds.changeScale(i,t.pos),this.graph.change()}#b(){const e=this.#a;e&&(this.#a=null,this.read_only=e.readOnly)}processMouseMove(e){if(this.dragZoomEnabled&&e.ctrlKey&&e.shiftKey&&this.#a){this.#v(e);return}this.autoresize&&this.resize(),this.set_canvas_dirty_on_mouse_event&&(this.dirty_canvas=!0);const{graph:t,resizingGroup:n,linkConnector:i,pointer:s,subgraph:a}=this;if(!t)return;L.active_canvas=this,this.adjustMouseEvent(e);const r=[e.clientX,e.clientY];this.mouse[0]=r[0],this.mouse[1]=r[1];const l=[r[0]-this.last_mouse[0],r[1]-this.last_mouse[1]];this.last_mouse=r;const{canvasX:d,canvasY:u}=e;this.graph_mouse[0]=d,this.graph_mouse[1]=u,e.isPrimary&&s.move(e);let p=te.Nothing;if(a&&(p|=a.inputNode.onPointerMove(e),p|=a.outputNode.onPointerMove(e)),this.block_click){e.preventDefault();return}if(e.dragging=this.last_mouse_dragging,this.node_widget){const[f,y]=this.node_widget;if(y?.mouse){const b=d-f.pos[0],v=u-f.pos[1],k=y.mouse(e,[b,v],f);k!=null&&(this.dirty_canvas=k)}}const m=t.getNodeOnPos(d,u,this.visible_nodes),g=this.dragging_rectangle;if(g)g[2]=d-g[0],g[3]=u-g[1],this.dirty_canvas=!0;else if(n)p|=te.Group,s.resizeDirection="SE";else if(this.dragging_canvas)this.ds.offset[0]+=l[0]/this.ds.scale,this.ds.offset[1]+=l[1]/this.ds.scale,this.#r();else if((this.allow_interaction||m?.flags.allow_interaction)&&!this.read_only){if(i.isConnecting&&(this.dirty_canvas=!0),this.updateMouseOverNodes(m,e),m){p|=te.Node,m.redraw_on_mouse&&(this.dirty_canvas=!0);const f=[0,0];let y=-1,b=-1;const v=D.querySlotAtPoint({x:d,y:u});v&&v.nodeId===String(m.id)?v.type==="input"?(y=v.index,f[0]=v.position.x,f[1]=v.position.y):(b=v.index,f[0]=v.position.x,f[1]=v.position.y):(y=vs(m,d,u,f),b=ks(m,d,u,f));const k=m.getWidgetOnPos(d,u,!0)??void 0;if(!m.mouseOver){m.mouseOver={},this.node_over=m,this.dirty_canvas=!0;for(const S of this.#s)S.hideSlots(),this.dirty_bgcanvas=!0;m.onMouseEnter?.(e)}m.onMouseMove?.(e,[d-m.pos[0],u-m.pos[1]],this);const{mouseOver:w}=m;if(w.inputId!==y||w.outputId!==b||w.overWidget!==k){if(w.inputId=y,w.outputId=b,w.overWidget=k,i.overWidget=void 0,i.isConnecting){const S=i.renderLinks.at(0);let E,C;if(!(!S||!i.isNodeValidDrop(m))){if(i.state.connectingTo==="input"){if(k){const I=m.getSlotFromWidget(k);if(I&&i.isInputValidDrop(m,I)){if(C=I,_.vueNodesMode){const P=m.inputs.indexOf(I);E=P!==-1?ae(m,P,!0):m.getInputSlotPos(I)}else E=m.getInputSlotPos(I);i.overWidget=k}}if(!i.overWidget){if(y===-1&&b===-1){const I=m.findInputByType(S.fromSlot.type);I&&(C=I.slot,E=_.vueNodesMode?ae(m,I.index,!0):m.getInputSlotPos(I.slot))}else y!=-1&&m.inputs[y]&&_.isValidConnection(S.fromSlot.type,m.inputs[y].type)&&(E=f,C=m.inputs[y]);if(C){const I=m.getWidgetFromSlot(C);I&&(i.overWidget=I)}}}else if(i.state.connectingTo==="output")if(y===-1&&b===-1){const I=m.findOutputByType(S.fromSlot.type);I&&(E=_.vueNodesMode?ae(m,I.index,!1):m.getOutputPos(I.index))}else b!=-1&&m.outputs[b]&&_.isValidConnection(S.fromSlot.type,m.outputs[b].type)&&(E=f)}this._highlight_pos=E,this._highlight_input=C}this.dirty_canvas=!0}s.eDown||(y===-1&&b===-1&&!k?s.resizeDirection=m.findResizeDirection(d,u):s.resizeDirection&&=void 0)}else{p=this.#S(p);const f=this.#T(e);if(this.over_link_center!==f&&(p|=te.Link,this.over_link_center=f,this.dirty_bgcanvas=!0),this.canvas){const y=t.getGroupOnPos(d,u);y&&!e.ctrlKey&&!this.read_only&&y.isInResize(d,u)?s.resizeDirection="SE":s.resizeDirection&&=void 0}}if(this.node_capturing_input&&this.node_capturing_input!=m&&this.node_capturing_input.onMouseMove?.(e,[d-this.node_capturing_input.pos[0],u-this.node_capturing_input.pos[1]],this),this.isDragging){const f=this.selectedItems,y=e.ctrlKey?f:yn(f),b=l[0]/this.ds.scale,v=l[1]/this.ds.scale;if(_.vueNodesMode)this.moveChildNodesInGroupVueMode(y,b,v);else for(const k of y)k.move(b,v,!0);this.#r()}}this.hoveringOver=p,e.preventDefault()}#S(e){const{graph:t,pointer:n,linkConnector:i}=this;if(!t)throw new N;if(n.isDown){if(i.isConnecting){for(const s of this.#s)if(s.containsPoint(this.graph_mouse))return i.isRerouteValidDrop(s)&&(i.overReroute=s,this._highlight_pos=s.pos),e|=te.RerouteSlot}}else{let s=!1;for(const a of this.#s)s||=a.updateVisibility(this.graph_mouse),a.isSlotHovered&&(e|=te.RerouteSlot);s&&(this.dirty_bgcanvas=!0)}return this._highlight_pos&&=void 0,i.overReroute&&=void 0,e}#h(e,t,n=!1){this.emitBeforeChange(),this.graph?.beforeChange(),t.finally=()=>{this.isDragging=!1,this.graph?.afterChange(),this.emitAfterChange()},this.processSelect(e,t.eDown,n),this.isDragging=!0}#g(e){const{graph:t}=this;(e.shiftKey||_.alwaysSnapToGrid)&&t?.snapToGrid(this.selectedItems),this.dirty_canvas=!0,this.dirty_bgcanvas=!0,this.onNodeMoved?.(Ts(this.selectedItems))}processMouseUp(e){if(e.isPrimary===!1)return;const{graph:t,pointer:n}=this;if(t){if(this.#b(),L.active_canvas=this,this.adjustMouseEvent(e),e.click_time=_.getTime()-this.last_mouseclick,n.up(e)===!0){n.isDown=!1,n.isDouble=!1,this.connecting_links=null,this.dragging_canvas=!1,t.change(),e.stopPropagation(),e.preventDefault();return}if(this.last_mouse_dragging=!1,this.last_click_position=null,this.block_click&&=!1,e.button===0){this.selected_group=null,this.isDragging=!1;const i=e.canvasX,s=e.canvasY;this.linkConnector.isConnecting||(this.dirty_canvas=!0,this.node_over?.onMouseUp?.(e,[i-this.node_over.pos[0],s-this.node_over.pos[1]],this),this.node_capturing_input?.onMouseUp?.(e,[i-this.node_capturing_input.pos[0],s-this.node_capturing_input.pos[1]],this))}else e.button===1?(this.dirty_canvas=!0,this.dragging_canvas=!1):e.button===2&&(this.dirty_canvas=!0);n.isDown=!1,n.isDouble=!1,t.change(),e.stopPropagation(),e.preventDefault()}}processMouseOut(e){this.adjustMouseEvent(e),this.updateMouseOverNodes(null,e)}processMouseCancel(){console.warn("Pointer cancel!"),this.pointer.reset()}processMouseWheel(e){if(!this.graph||!this.allow_dragcanvas)return;this.adjustMouseEvent(e);const t=[e.clientX,e.clientY];if(this.viewport&&!We(t,this.viewport))return;let{scale:n}=this.ds;const i=this.pointer.isTrackpadGesture(e);if((e.ctrlKey||e.metaKey&&navigator.platform.includes("Mac"))&&!e.altKey&&!e.shiftKey||_.mouseWheelScroll==="zoom")i?(n*=1+e.deltaY*(1-this.zoom_speed)*.18,this.ds.changeScale(n,[e.clientX,e.clientY],!1)):(e.deltaY<0?n*=this.zoom_speed:e.deltaY>0&&(n*=1/this.zoom_speed),this.ds.changeScale(n,[e.clientX,e.clientY]));else{const s=i?.18:.008333;!i&&e.shiftKey&&e.deltaX===0?this.ds.offset[0]-=e.deltaY*(1+s)*(1/n):(this.ds.offset[0]-=e.deltaX*(1+s)*(1/n),this.ds.offset[1]-=e.deltaY*(1+s)*(1/n))}this.graph.change(),e.preventDefault()}#I(){const e=new CustomEvent("litegraph:no-items-selected",{bubbles:!0});this.canvas.dispatchEvent(e)}processKey(e){this.#d=e.shiftKey;const{graph:t}=this;if(!t)return;let n=!1;if(e.target.localName!="input"){if(e.type=="keydown"){if(e.key===" ")this.read_only=!0,this._previously_dragging_canvas===null&&(this._previously_dragging_canvas=this.dragging_canvas),this.dragging_canvas=this.pointer.isDown,n=!0;else if(e.key==="Escape"){if(this.linkConnector.isConnecting){this.linkConnector.reset(),e.preventDefault();return}this.node_panel?.close(),this.options_panel?.close(),(this.node_panel||this.options_panel)&&(n=!0)}else if(e.keyCode===65&&e.ctrlKey)this.selectItems(),n=!0;else if(e.keyCode===67&&(e.metaKey||e.ctrlKey)&&!e.shiftKey)this.selected_nodes&&(this.copyToClipboard(),n=!0);else if(e.keyCode===86&&(e.metaKey||e.ctrlKey))this.pasteFromClipboard({connectInputs:e.shiftKey});else if((e.key==="Delete"||e.key==="Backspace")&&e.target.localName!="input"&&e.target.localName!="textarea"){if(this.selectedItems.size===0){this.#I();return}this.deleteSelected(),n=!0}for(const i of Object.values(this.selected_nodes))i.onKeyDown?.(e)}else if(e.type=="keyup"){e.key===" "&&(this.read_only=!1,this.dragging_canvas=(this._previously_dragging_canvas??!1)&&this.pointer.isDown,this._previously_dragging_canvas=null);for(const i of Object.values(this.selected_nodes))i.onKeyUp?.(e)}t.change(),n&&(e.preventDefault(),e.stopImmediatePropagation())}}_serializeItems(e){const t={nodes:[],groups:[],reroutes:[],links:[],subgraphs:[]},n=new Set;for(const i of e??this.selectedItems)if(i instanceof q){if(i.clonable===!1)continue;const s=i.clone()?.serialize();if(!s)continue;if(s.id=i.id,t.nodes.push(s),i.inputs)for(const{link:a}of i.inputs){if(a==null)continue;const r=this.graph?._links.get(a)?.asSerialisable();r&&t.links.push(r)}i instanceof gt&&n.add(i.subgraph)}else i instanceof de?t.groups.push(i.serialize()):i instanceof J&&t.reroutes.push(i.asSerialisable());for(const i of n){for(const a of i.nodes)a instanceof gt&&n.add(a.subgraph);const s=i.clone(!0).asSerialisable();t.subgraphs.push(s)}return t}copyToClipboard(e){const t=JSON.stringify(this._serializeItems(e));return localStorage.setItem("litegrapheditor_clipboard",t),t}emitEvent(e){this.canvas.dispatchEvent(new CustomEvent("litegraph:canvas",{bubbles:!0,detail:e}))}emitBeforeChange(){this.emitEvent({subType:"before-change"})}emitAfterChange(){this.emitEvent({subType:"after-change"})}_pasteFromClipboard(e={}){const t=localStorage.getItem("litegrapheditor_clipboard");if(t)return this._deserializeItems(JSON.parse(t),e)}_deserializeItems(e,t){const{connectInputs:n=!1,position:i=this.graph_mouse}=t;if(!_.ctrl_shift_v_paste_connect_unselected_outputs&&n)return;const{graph:s}=this;if(!s)throw new N;s.beforeChange(),this.emitBeforeChange(),e.nodes??=[],e.groups??=[],e.reroutes??=[],e.links??=[],e.subgraphs??=[];let a=1/0,r=1/0;for(const b of[...e.nodes,...e.reroutes]){if(b.pos==null)throw new TypeError("Invalid node encountered on paste. `pos` was null.");b.pos[0]<a&&(a=b.pos[0]),b.pos[1]<r&&(r=b.pos[1])}if(e.groups)for(const b of e.groups)b.bounding[0]<a&&(a=b.bounding[0]),b.bounding[1]<r&&(r=b.bounding[1]);const l={created:[],nodes:new Map,links:new Map,reroutes:new Map,subgraphs:new Map},{created:d,nodes:u,links:p,reroutes:m}=l,g={};for(const b of e.subgraphs)b.id=g[b.id]=fe();const f=[e.nodes?[e.nodes]:[],e.subgraphs?e.subgraphs.map(b=>b.nodes??[]):[]].flat(2);for(const b of f)b.type in g&&(b.type=g[b.type]);for(const b of e.subgraphs){const v=s.createSubgraph(b);l.subgraphs.set(b.id,v)}for(const b of e.subgraphs)l.subgraphs.get(b.id)?.configure(b);for(const b of e.groups){b.id=-1;const v=new de;v.configure(b),s.add(v),d.push(v)}for(const b of e.nodes){const v=b.type==null?null:_.createNode(b.type);v&&(u.set(b.id,v),b.id=-1,v.configure(b),s.add(v),d.push(v))}for(const b of e.reroutes){const{id:v,...k}=b,w=s.setReroute(k);d.push(w),m.set(v,w)}for(const b of m.values()){if(b.parentId==null)continue;const v=m.get(b.parentId);v&&(b.parentId=v.id)}for(const b of e.links){let v=u.get(b.origin_id),k;b.parentId!=null&&(k=m.get(b.parentId)?.id),n&&_.ctrl_shift_v_paste_connect_unselected_outputs&&(v??=s.getNodeById(b.origin_id),k??=b.parentId);const w=u.get(b.target_id);if(w){const S=v?.connect(b.origin_slot,w,b.target_slot,k);S&&p.set(b.id,S)}}for(const b of m.values()){const v=[...b.linkIds].map(k=>p.get(k)?.id??k);b.update(b.parentId,void 0,v,b.floating),b.validateLinks(s.links,s.floatingLinks)||s.removeReroute(b.id)}for(const b of d)b.pos[0]+=i[0]-a,b.pos[1]+=i[1]-r;const y=d.filter(b=>b instanceof q).map(b=>{const v=b.size?.[1]??200,k=_.vueNodesMode?on(v):v;return{nodeId:String(b.id),bounds:{x:b.pos[0],y:b.pos[1],width:b.size?.[0]??100,height:k}}});return y.length&&D.setSource(ue.Canvas),D.batchUpdateNodeBounds(y),this.selectItems(d),Ge(s,b=>b.onGraphConfigured?.()),Ge(s,b=>b.onAfterGraphConfigured?.()),s.afterChange(),this.emitAfterChange(),l}pasteFromClipboard(e={}){this.emitBeforeChange();try{this._pasteFromClipboard(e)}finally{this.emitAfterChange()}}processNodeDblClicked(e){this.onShowNodePanel?.(e),this.onNodeDblClicked?.(e),this.setDirty(!0)}#k(e){const t=Math.abs(e[2]),n=Math.abs(e[3]);return e[2]<0&&(e[0]-=t),e[3]<0&&(e[1]-=n),e[2]=t,e[3]=n,e}#w(e){const{graph:t,subgraph:n}=this;if(!t)throw new N;const i=new Set;if(n){const{inputNode:s,outputNode:a}=n;Le(e,s.boundingRect)&&i.add(s),Le(e,a.boundingRect)&&i.add(a)}for(const s of t._nodes)Le(e,s.boundingRect)&&i.add(s);for(const s of t.groups)en(e,s._bounding)&&(s.recomputeInsideNodes(),i.add(s));for(const s of t.reroutes.values())We(s.pos,e)&&i.add(s);return i}handleLiveSelect(e,t,n){t[2]=e.canvasX-t[0],t[3]=e.canvasY-t[1];const i=[t[0],t[1],t[2],t[3]];this.#k(i);const s=this.#w(i),a=new Set;if(e.shiftKey&&!e.altKey){for(const l of n)a.add(l);for(const l of s)a.add(l)}else if(e.altKey&&!e.shiftKey)for(const l of n)s.has(l)||a.add(l);else for(const l of s)a.add(l);let r=!1;for(const l of[...this.selectedItems])a.has(l)||(this.deselect(l),r=!0);for(const l of a)this.selectedItems.has(l)||(this.select(l),r=!0);r&&(this.onSelectionChange?.(this.selected_nodes),this.setDirty(!0))}finalizeLiveSelect(){this.onSelectionChange?.(this.selected_nodes)}#C(e,t){const n=[t[0],t[1],t[2],t[3]];this.#k(n);const i=this.#w(n),{selectedItems:s}=this;if(e.shiftKey)for(const a of i)this.select(a);else if(e.altKey)for(const a of i)this.deselect(a);else{for(const a of s.values())i.has(a)||this.deselect(a);for(const a of i)this.select(a)}this.onSelectionChange?.(this.selected_nodes)}processSelect(e,t,n=!1){const i=t?.shiftKey,s=t!=null&&(t.metaKey||t.ctrlKey),a=i||s,r=a||this.multi_select;if(!e)(!a||this.multi_select)&&this.deselectAll();else if(!e.selected||!this.selectedItems.has(e))r||this.deselectAll(e),this.select(e);else if(r&&!n)this.deselect(e);else if(!n)this.deselectAll(e);else return;this.onSelectionChange?.(this.selected_nodes),this.setDirty(!0)}select(e){if(!(e.selected&&this.selectedItems.has(e))&&(e.selected=!0,this.selectedItems.add(e),this.state.selectionChanged=!0,e instanceof q)){if(e.onSelected?.(),this.selected_nodes[e.id]=e,this.onNodeSelected?.(e),e.inputs)for(const t of e.inputs)t.link!=null&&(this.highlighted_links[t.link]=!0);if(e.outputs)for(const t of e.outputs.flatMap(n=>n.links))t!=null&&(this.highlighted_links[t]=!0)}}deselect(e){if(!e.selected&&!this.selectedItems.has(e)||(e.selected=!1,this.selectedItems.delete(e),this.state.selectionChanged=!0,!(e instanceof q)))return;e.onDeselected?.(),delete this.selected_nodes[e.id],this.onNodeDeselected?.(e);const{graph:t}=this;if(t){if(e.inputs)for(const n of e.inputs){if(n.link==null)continue;const i=z.getOriginNode(t,n.link);i&&this.selectedItems.has(i)||delete this.highlighted_links[n.link]}if(e.outputs)for(const n of e.outputs.flatMap(i=>i.links)){if(n==null)continue;const i=z.getTargetNode(t,n);i&&this.selectedItems.has(i)||delete this.highlighted_links[n]}}}processNodeSelected(e,t){this.processSelect(e,t,t&&(t.shiftKey||t.metaKey||t.ctrlKey||this.multi_select))}selectNode(e,t){e==null?this.deselectAll():this.selectNodes([e],t)}get empty(){if(!this.graph)throw new N;return this.graph.empty}get positionableItems(){if(!this.graph)throw new N;return this.graph.positionableItems()}selectItems(e,t){const n=e??this.positionableItems;t||this.deselectAll();for(const i of n)this.select(i);this.onSelectionChange?.(this.selected_nodes),this.setDirty(!0)}selectNodes(e,t){this.selectItems(e,t)}deselectNode(e){this.deselect(e)}deselectAll(e){if(!this.graph)return;const t=this.selectedItems;if(!t.size)return;const n=t.size;let i;for(const a of t){if(a===e){i=a;continue}a.onDeselected?.(),a.selected=!1}t.clear(),i&&t.add(i),this.setDirty(!0);const s=e?.id==null?null:this.selected_nodes[e.id];if(this.selected_nodes={},this.current_node=null,this.highlighted_links={},e instanceof q){if(s&&(this.selected_nodes[s.id]=s),e.inputs)for(const a of e.inputs)a.link!=null&&(this.highlighted_links[a.link]=!0);if(e.outputs)for(const a of e.outputs.flatMap(r=>r.links))a!=null&&(this.highlighted_links[a]=!0)}n!==t.size&&(this.state.selectionChanged=!0,this.onSelectionChange?.(this.selected_nodes))}deselectAllNodes(){this.deselectAll()}deleteSelected(){const{graph:e}=this;if(!e)throw new N;this.emitBeforeChange(),e.beforeChange();for(const t of this.selectedItems)if(t instanceof q){const n=t;if(n.block_delete)continue;n.connectInputToOutput(),e.remove(n),this.onNodeDeselected?.(n)}else t instanceof de?e.remove(t):t instanceof J&&e.removeReroute(t.id);this.selected_nodes={},this.selectedItems.clear(),this.current_node=null,this.highlighted_links={},this.state.selectionChanged=!0,this.onSelectionChange?.(this.selected_nodes),this.setDirty(!0),e.afterChange(),this.emitAfterChange()}deleteSelectedNodes(){this.deleteSelected()}centerOnNode(e){const t=window?.devicePixelRatio||1;this.ds.offset[0]=-e.pos[0]-e.size[0]*.5+this.canvas.width*.5/(this.ds.scale*t),this.ds.offset[1]=-e.pos[1]-e.size[1]*.5+this.canvas.height*.5/(this.ds.scale*t),this.setDirty(!0,!0)}adjustMouseEvent(e){let t=e.clientX,n=e.clientY;if(this.canvas){const i=this.canvas.getBoundingClientRect();t-=i.left,n-=i.top}e.safeOffsetX=t,e.safeOffsetY=n,e.deltaX===void 0&&(e.deltaX=t-this.last_mouse_position[0]),e.deltaY===void 0&&(e.deltaY=n-this.last_mouse_position[1]),this.last_mouse_position[0]=t,this.last_mouse_position[1]=n,e.canvasX=t/this.ds.scale-this.ds.offset[0],e.canvasY=n/this.ds.scale-this.ds.offset[1]}setZoom(e,t){this.ds.changeScale(e,t),this.#r()}convertOffsetToCanvas(e,t){return this.ds.convertOffsetToCanvas(e)}convertCanvasToOffset(e,t){return this.ds.convertCanvasToOffset(e,t)}convertEventToCanvasOffset(e){const t=this.canvas.getBoundingClientRect();return this.convertCanvasToOffset([e.clientX-t.left,e.clientY-t.top])}bringToFront(e){const{graph:t}=this;if(!t)throw new N;const n=t._nodes.indexOf(e);n!=-1&&(t._nodes.splice(n,1),t._nodes.push(e))}sendToBack(e){const{graph:t}=this;if(!t)throw new N;const n=t._nodes.indexOf(e);n!=-1&&(t._nodes.splice(n,1),t._nodes.unshift(e))}computeVisibleNodes(e,t){const n=t||[];if(n.length=0,!this.graph)throw new N;const i=e||this.graph._nodes;for(const s of i)s.updateArea(this.ctx),Le(this.visible_area,s.renderArea)&&n.push(s);return n}isNodeVisible(e){return this.#n.has(e.id)}draw(e,t){if(!this.canvas||this.canvas.width==0||this.canvas.height==0)return;const n=_.getTime();if(this.render_time=(n-this.last_draw_time)*.001,this.last_draw_time=n,this.graph&&this.ds.computeVisibleArea(this.viewport),this.dirty_canvas||e){this.computeVisibleNodes(void 0,this.visible_nodes),this.#n=new Set(this.visible_nodes.map(s=>s.id));const{subgraph:i}=this;i&&(i.inputNode.arrange(),i.outputNode.arrange())}(this.dirty_bgcanvas||t||this.always_render_background||this.graph?._last_trigger_time&&n-this.graph._last_trigger_time<1e3)&&this.drawBackCanvas(),(this.dirty_canvas||e)&&this.drawFrontCanvas(),this.fps=this.render_time?1/this.render_time:0,this.frame++}drawFrontCanvas(){this.dirty_canvas=!1;const{ctx:e,canvas:t,graph:n,linkConnector:i}=this;e.start2D&&!this.viewport&&(e.start2D(),e.restore(),e.setTransform(1,0,0,1,0,0));const s=this.viewport||this.dirty_area;if(s&&(e.save(),e.beginPath(),e.rect(s[0],s[1],s[2],s[3]),e.clip()),this.#i=this.#d||_.alwaysSnapToGrid?this.graph?.getSnapToGridSize():void 0,this.clear_background&&(s?e.clearRect(s[0],s[1],s[2],s[3]):e.clearRect(0,0,t.width,t.height)),this.bgcanvas==this.canvas)this.drawBackCanvas();else{const a=window.devicePixelRatio;e.drawImage(this.bgcanvas,0,0,this.bgcanvas.width/a,this.bgcanvas.height/a)}if(this.onRender?.(t,e),this.show_info){const a=this.fpsInfoLocation??s;this.renderInfo(e,a?.[0]??0,a?.[1]??0)}if(n){e.save(),this.ds.toCanvasContext(e);const{visible_nodes:a}=this,r=this.#i&&(this.isDragging||D.isDraggingVueNodes.value);for(const l of a)e.save(),r&&this.selectedItems.has(l)&&this.drawSnapGuide(e,l),e.translate(l.pos[0],l.pos[1]),this.drawNode(l,e),e.restore();if(this.subgraph?.draw(e,this.colourGetter,this.linkConnector.renderLinks[0]?.fromSlot,this.editor_alpha),this.render_execution_order&&this.drawExecutionOrder(e),n.config.links_ontop&&this.drawConnections(e),i.isConnecting){const{renderLinks:l}=i,d=this.#L();e.lineWidth=this.connections_width;for(const u of l){const{fromSlot:p,fromPos:m,fromDirection:g,dragDirection:f}=u,y=p.shape,b=p.type,v=Fw(b);this.linkRenderer&&this.linkRenderer.renderDraggingLink(e,m,d,v,g,f,{...this.buildLinkRenderContext(),linkMarkerShape:re.None}),e.fillStyle=v,e.beginPath(),b===_.EVENT||y===M.BOX?(e.rect(m[0]-6+.5,m[1]-5+.5,14,10),e.rect(d[0]-6+.5,d[1]-5+.5,14,10)):y===M.ARROW?(e.moveTo(m[0]+8,m[1]+.5),e.lineTo(m[0]-4,m[1]+6+.5),e.lineTo(m[0]-4,m[1]-6+.5),e.closePath()):(e.arc(m[0],m[1],4,0,Math.PI*2),e.arc(d[0],d[1],4,0,Math.PI*2)),e.fill()}this.#E(e,d)}!this.isDragging&&this.over_link_center&&this.render_link_tooltip?this.drawLinkTooltip(e,this.over_link_center):this.onDrawLinkTooltip?.(e,null),this.onDrawForeground?.(e,this.visible_area),e.restore()}this.onDrawOverlay?.(e),s&&e.restore()}#T(e){if(this.linkMarkerShape!==re.None)for(const t of this.renderedPaths){const n=t._pos;if(n&&G(e.canvasX,e.canvasY,n[0]-4,n[1]-4,8,8))return t}}#L(){return _.snaps_for_comfy?this.linkConnector.state.snapLinksPos??this._highlight_pos??this.graph_mouse:this.graph_mouse}#E(e,t){const n=!!this.linkConnector.state.snapLinksPos;if(!this._highlight_pos&&!n)return;e.fillStyle="#ffcc00",e.beginPath(),this._highlight_input?.shape===M.ARROW?(e.moveTo(t[0]+8,t[1]+.5),e.lineTo(t[0]-4,t[1]+6+.5),e.lineTo(t[0]-4,t[1]-6+.5),e.closePath()):e.arc(t[0],t[1],6,0,Math.PI*2),e.fill();const{linkConnector:i}=this,{overReroute:s,overWidget:a}=i;if(!_.snap_highlights_node||!i.isConnecting||n)return;s?.drawHighlight(e,"#ffcc00aa");const r=this.node_over;if(!r)return;const{strokeStyle:l,lineWidth:d}=e,u=r.boundingRect,p=3,m=_.ROUND_RADIUS+p,g=u[0]-p,f=u[1]-p,y=u[2]+p*2,b=u[3]+p*2;e.beginPath(),e.roundRect(g,f,y,b,m);const v=i.state.connectingTo==="output"?0:1,k=v?-1:1,w=t[0],S=t[1],E=y<b?y:y*Math.max(b/y,.5),C=e.createRadialGradient(w,S,0,w,S,E);C.addColorStop(1,"#00000000"),C.addColorStop(0,"#ffcc00aa");const I=e.createLinearGradient(g,f,g+y,f);if(I.addColorStop(.5,"#00000000"),I.addColorStop(v+.67*k,"#ddeeff33"),I.addColorStop(v+k,"#ffcc0055"),e.setLineDash([m,m*.001]),e.lineWidth=1,e.strokeStyle=I,e.stroke(),a){const{computedHeight:P}=a;e.beginPath();const{pos:[A,F]}=r,T=_.NODE_WIDGET_HEIGHT;a.type.startsWith("custom")&&P!=null&&P>T*2?e.rect(A+9,F+a.y+9,(a.width??u[2])-18,P-18):e.roundRect(A+B.margin,F+a.y,a.width??u[2],T,T*.5),e.stroke()}e.strokeStyle=C,e.stroke(),e.setLineDash([]),e.lineWidth=d,e.strokeStyle=l}renderInfo(e,t,n){t=t||10,n=n||this.canvas.offsetHeight-80,e.save(),e.translate(t,n),e.font=`10px ${_.DEFAULT_FONT}`,e.fillStyle="#888",e.textAlign="left",this.graph?(e.fillText(`T: ${this.graph.globaltime.toFixed(2)}s`,5,13),e.fillText(`I: ${this.graph.iteration}`,5,26),e.fillText(`N: ${this.graph._nodes.length} [${this.visible_nodes.length}]`,5,39),e.fillText(`V: ${this.graph._version}`,5,52),e.fillText(`FPS:${this.fps.toFixed(2)}`,5,65)):e.fillText("No graph selected",5,13),e.restore()}drawBackCanvas(){const e=this.bgcanvas;(e.width!=this.canvas.width||e.height!=this.canvas.height)&&(e.width=this.canvas.width,e.height=this.canvas.height),this.bgctx||(this.bgctx=this.bgcanvas.getContext("2d"));const t=this.bgctx;if(!t)throw new TypeError("Background canvas context was null.");const n=this.viewport||[0,0,t.canvas.width,t.canvas.height];this.clear_background&&t.clearRect(n[0],n[1],n[2],n[3]);const i=this.onRenderBackground?this.onRenderBackground(e,t):!1;if(!this.viewport){const s=window.devicePixelRatio;t.restore(),t.setTransform(s,0,0,s,0,0)}if(this.graph){if(t.save(),this.ds.toCanvasContext(t),this.ds.scale<1.5&&!i&&this.clear_background_color&&(t.fillStyle=this.clear_background_color,t.fillRect(this.visible_area[0],this.visible_area[1],this.visible_area[2],this.visible_area[3])),this.background_image&&this.ds.scale>.5&&!i){this.zoom_modify_alpha?t.globalAlpha=(1-.5/this.ds.scale)*this.editor_alpha:t.globalAlpha=this.editor_alpha,t.imageSmoothingEnabled=!1,(!this._bg_img||this._bg_img.name!=this.background_image)&&(this._bg_img=new Image,this._bg_img.name=this.background_image,this._bg_img.src=this.background_image,this._bg_img.addEventListener("load",()=>{this.draw(!0,!0)}));let s=this._pattern;s==null&&this._bg_img.width>0&&(s=t.createPattern(this._bg_img,"repeat")??void 0,this._pattern_img=this._bg_img,this._pattern=s),s&&(t.fillStyle=s,t.fillRect(this.visible_area[0],this.visible_area[1],this.visible_area[2],this.visible_area[3]),t.fillStyle="transparent"),t.globalAlpha=1,t.imageSmoothingEnabled=!0}this.bg_tint&&(t.fillStyle=this.bg_tint,t.fillRect(this.visible_area[0],this.visible_area[1],this.visible_area[2],this.visible_area[3]),t.fillStyle="transparent"),this.graph._groups.length&&this.drawGroups(e,t),this.onDrawBackground?.(t,this.visible_area),this.render_canvas_border&&(t.strokeStyle="#235",t.strokeRect(0,0,e.width,e.height)),this.render_connections_shadows?(t.shadowColor="#000",t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowBlur=6):t.shadowColor="rgba(0,0,0,0)",this.drawConnections(t),t.shadowColor="rgba(0,0,0,0)",t.restore()}this.dirty_bgcanvas=!1,this.dirty_canvas=!0}drawNode(e,t){if(this.current_node=e,_.vueNodesMode){e._setConcreteSlots(),e.collapsed||e.arrange();return}const n=e.renderingColor,i=e.renderingBgColor;if(t.globalAlpha=this.getNodeModeAlpha(e),this.render_shadows&&!this.low_quality?(t.shadowColor=_.DEFAULT_SHADOW_COLOR,t.shadowOffsetX=2*this.ds.scale,t.shadowOffsetY=2*this.ds.scale,t.shadowBlur=3*this.ds.scale):t.shadowColor="transparent",e.flags.collapsed&&e.onDrawCollapsed?.(t,this)==!0)return;const s=e._shape||M.BOX,a=Bw;if(a[0]=e.renderingSize[0],a[1]=e.renderingSize[1],e.collapsed&&(t.font=this.inner_text_font),e.clip_area&&(t.save(),t.beginPath(),s==M.BOX?t.rect(0,0,a[0],a[1]):s==M.ROUND?t.roundRect(0,0,a[0],a[1],[10]):s==M.CIRCLE&&t.arc(a[0]*.5,a[1]*.5,a[0]*.5,0,Math.PI*2),t.clip()),this.drawNodeShape(e,t,a,n,i,!!e.selected),e.title_buttons&&!e.flags.collapsed){const r=_.NODE_TITLE_HEIGHT;let l=a[0];for(let d=0;d<e.title_buttons.length;d++){const u=e.title_buttons[d];if(!u.visible)continue;const p=u.getWidth(t);l-=p;const m=-r+(r-u.height)/2;u.draw(t,l,m),l-=2}}this.low_quality||e.drawBadges(t),t.shadowColor="transparent",t.strokeStyle=_.NODE_BOX_OUTLINE_COLOR,e.onDrawForeground?.(t,this,this.canvas),t.font=this.inner_text_font,e._setConcreteSlots(),e.collapsed?this.render_collapsed_slots&&e.drawCollapsedSlots(t):(e.arrange(),e.drawSlots(t,{fromSlot:this.linkConnector.renderLinks[0]?.fromSlot,colorContext:this.colourGetter,editorAlpha:this.editor_alpha,lowQuality:this.low_quality}),t.textAlign="left",t.globalAlpha=1,this.drawNodeWidgets(e,null,t)),e.clip_area&&t.restore(),t.globalAlpha=1}drawLinkTooltip(e,t){const n=t._pos;if(e.fillStyle="black",e.beginPath(),this.linkMarkerShape===re.Arrow){const l=e.getTransform();e.translate(n[0],n[1]),Number.isFinite(t._centreAngle)&&e.rotate(t._centreAngle),e.moveTo(-2,-3),e.lineTo(4,0),e.lineTo(-2,3),e.setTransform(l)}else(this.linkMarkerShape==null||this.linkMarkerShape===re.Circle)&&e.arc(n[0],n[1],3,0,Math.PI*2);e.fill();const{data:i}=t;if(i==null||this.onDrawLinkTooltip?.(e,t,this)==!0)return;let s=null;if(typeof i=="number"?s=i.toFixed(2):typeof i=="string"?s=`"${i}"`:typeof i=="boolean"?s=String(i):i.toToolTip?s=i.toToolTip():s=`[${i.constructor.name}]`,s==null)return;s=s.substring(0,30),e.font="14px Courier New";const a=e.measureText(s).width+20,r=24;e.shadowColor="black",e.shadowOffsetX=2,e.shadowOffsetY=2,e.shadowBlur=3,e.fillStyle="#454",e.beginPath(),e.roundRect(n[0]-a*.5,n[1]-15-r,a,r,[3]),e.moveTo(n[0]-10,n[1]-15),e.lineTo(n[0]+10,n[1]-15),e.lineTo(n[0],n[1]-5),e.fill(),e.shadowColor="transparent",e.textAlign="center",e.fillStyle="#CEC",e.fillText(s,n[0],n[1]-15-r*.3)}drawNodeShape(e,t,n,i,s,a){t.strokeStyle=i,t.fillStyle=s;const r=_.NODE_TITLE_HEIGHT,{low_quality:l}=this,{collapsed:d}=e.flags,u=e.renderingShape,{title_mode:p}=e,m=!(p==se.TRANSPARENT_TITLE||p==se.NO_TITLE),g=Vw;g.set(e.boundingRect),g[0]-=e.pos[0],g[1]-=e.pos[1];const f=t.globalAlpha;t.beginPath(),u==M.BOX||l?t.rect(g[0],g[1],g[2],g[3]):u==M.ROUND||u==M.CARD?t.roundRect(g[0],g[1],g[2],g[3],u==M.CARD?[_.ROUND_RADIUS,_.ROUND_RADIUS,0,0]:[_.ROUND_RADIUS]):u==M.CIRCLE&&t.arc(n[0]*.5,n[1]*.5,n[0]*.5,0,Math.PI*2),t.fill(),!d&&m&&(t.shadowColor="transparent",t.fillStyle="rgba(0,0,0,0.2)",t.fillRect(0,-1,g[2],2)),t.shadowColor="transparent",e.onDrawBackground?.(t),(m||p==se.TRANSPARENT_TITLE)&&(e.drawTitleBarBackground(t,{scale:this.ds.scale,low_quality:l}),e.drawTitleBox(t,{scale:this.ds.scale,low_quality:l,box_size:10}),t.globalAlpha=f,e.drawTitleText(t,{scale:this.ds.scale,default_title_color:this.node_title_color,low_quality:l}),e.onDrawTitle?.(t));for(const y of Object.values(e.strokeStyles)){const b=y.call(e);b&&gn(t,g,{shape:u,title_height:r,title_mode:p,collapsed:d,...b})}e.drawProgressBar(t),e.execute_triggered!=null&&e.execute_triggered>0&&e.execute_triggered--,e.action_triggered!=null&&e.action_triggered>0&&e.action_triggered--}drawSnapGuide(e,t,n=M.ROUND){const i=zw;i.set(t.boundingRect);const{pos:s}=t,a=s[0]-i[0],r=s[1]-i[1];i[0]+=a,i[1]+=r,this.#i&&xe(i,this.#i),i[0]-=a,i[1]-=r;const{globalAlpha:l}=e;e.globalAlpha=1,e.beginPath();const[d,u,p,m]=i;if(n===M.CIRCLE){const g=d+p*.5,f=u+m*.5,y=Math.min(p*.5,m*.5);e.arc(g,f,y,0,Math.PI*2)}else e.rect(d,u,p,m);e.lineWidth=.5,e.strokeStyle="#FFFFFF66",e.fillStyle="#FFFFFF22",e.fill(),e.stroke(),e.globalAlpha=l}drawConnections(e){if(this.renderedPaths.clear(),this.links_render_mode===ie.HIDDEN_LINK)return;const{graph:t,subgraph:n}=this;if(!t)throw new N;const i=[],s=_.getTime(),{visible_area:a}=this;$e[0]=a[0]-20,$e[1]=a[1]-20,$e[2]=a[2]+40,$e[3]=a[3]+40,e.lineWidth=this.connections_width,e.fillStyle="#AAA",e.strokeStyle="#AAA",e.globalAlpha=this.editor_alpha;const r=t._nodes;for(const d of r){const{inputs:u}=d;if(u?.length)for(const[p,m]of u.entries()){if(!m||m.link==null)continue;const g=m.link,f=t._links.get(g);if(!f)continue;const y=_.vueNodesMode?ae(d,p,!0):d.getInputPos(p),b=t.getNodeById(f.origin_id);if(b==null)continue;const v=f.origin_slot,k=v===-1?[b.pos[0]+10,b.pos[1]+10]:_.vueNodesMode?ae(b,v,!1):b.getOutputPos(v),w=b.outputs[v];w&&this.#y(e,f,k,y,i,s,w.dir,m.dir)}}if(n){for(const d of n.inputNode.slots)if(d.linkIds.length)for(const u of d.linkIds){const p=z.resolve(u,t);if(!p)continue;const{link:m,inputNode:g,input:f}=p;if(!g||!f)continue;const y=_.vueNodesMode?ae(g,m.target_slot,!0):g.getInputPos(m.target_slot);this.#y(e,m,d.pos,y,i,s,f.dir,f.dir)}for(const d of n.outputNode.slots){if(!d.linkIds.length)continue;const u=z.resolve(d.linkIds[0],t);if(!u)continue;const{link:p,outputNode:m,output:g}=u;if(!m||!g)continue;const f=_.vueNodesMode?ae(m,p.origin_slot,!1):m.getOutputPos(p.origin_slot);this.#y(e,p,f,d.pos,i,s,g.dir,d.dir)}}t.floatingLinks.size>0&&this.#N(e,t,i,s);const l=this.#s;l.clear(),i.sort((d,u)=>d.linkIds.size-u.linkIds.size);for(const d of i)l.add(d),this.#i&&this.isDragging&&this.selectedItems.has(d)&&this.drawSnapGuide(e,d,M.CIRCLE),d.draw(e,this._pattern),this.pointer.isDown||d.drawSlots(e);e.globalAlpha=1}getNodeModeAlpha(e){return e.mode===H.BYPASS?.2:e.mode===H.NEVER?.4:this.editor_alpha}#N(e,t,n,i){const{globalAlpha:s}=e;e.globalAlpha=s*.33;for(const a of t.floatingLinks.values()){const r=z.getReroutes(t,a),l=r[0],d=r.at(-1);if(!(!l||!d?.floating))if(d.floating.slotType==="input"){const u=t.getNodeById(a.target_id);if(!u)continue;const p=l.pos,m=_.vueNodesMode?ae(u,a.target_slot,!0):u.getInputPos(a.target_slot),g=u.inputs[a.target_slot]?.dir;l._dragging=!0,this.#y(e,a,p,m,n,i,O.CENTER,g,!0)}else{const u=t.getNodeById(a.origin_id);if(!u)continue;const p=_.vueNodesMode?ae(u,a.origin_slot,!1):u.getOutputPos(a.origin_slot),m=d.pos,g=u.outputs[a.origin_slot]?.dir;a._dragging=!0,this.#y(e,a,p,m,n,i,g,O.CENTER,!0)}}e.globalAlpha=s}#y(e,t,n,i,s,a,r,l,d=!1){const{graph:u,renderedPaths:p}=this;if(!u)return;const m=z.getReroutes(u,t),g=[n,...m.map(k=>k.pos),i],f=g.map(k=>k[0]),y=g.map(k=>k[1]);if(Te[0]=Math.min(...f),Te[1]=Math.min(...y),Te[2]=Math.max(...f)-Te[0],Te[3]=Math.max(...y)-Te[1],!Le(Te,$e))return;const b=r||O.RIGHT,v=l||O.LEFT;if(m.length){let k;const w=m.length;for(let E=0;E<w;E++){const C=m[E];if(!p.has(C)){p.add(C),s.push(C),C._colour=t.color||L.link_type_colors[t.type]||this.default_link_color;const I=u.getReroute(C.parentId)?.pos??n;C.calculateAngle(this.last_draw_time,u,I),C._dragging||this.renderLink(e,I,C.pos,t,!1,0,null,k===void 0?b:O.CENTER,O.CENTER,{startControl:k,endControl:C.controlPoint,reroute:C,disabled:d})}if(!k&&m.at(-1)?.floating?.slotType==="input")k=[0,0];else{const I=m[E+1]?.pos??i,P=Math.min(J.maxSplineOffset,Ue(C.pos,I)*.25);k=[P*C.cos,P*C.sin]}}if(t._dragging)return;const S=g.at(-2)??n;this.renderLink(e,S,i,t,!1,0,null,O.CENTER,v,{startControl:k,disabled:d})}else t._dragging||this.renderLink(e,n,i,t,!1,0,null,b,v);if(p.add(t),t?._last_time&&a-t._last_time<1e3){const k=2-(a-t._last_time)*.002,w=e.globalAlpha;e.globalAlpha=w*k,this.renderLink(e,n,i,t,!0,k,"white",b,v),e.globalAlpha=w}}buildLinkRenderContext(){return{renderMode:this.links_render_mode,connectionWidth:this.connections_width,renderBorder:this.render_connections_border,lowQuality:this.low_quality,highQualityRender:this.highquality_render,scale:this.ds.scale,linkMarkerShape:this.linkMarkerShape,renderConnectionArrows:this.render_connection_arrows,highlightedLinks:new Set(Object.keys(this.highlighted_links)),defaultLinkColor:this.default_link_color,linkTypeColors:L.link_type_colors,disabledPattern:this._pattern}}renderLink(e,t,n,i,s,a,r,l,d,{startControl:u,endControl:p,reroute:m,num_sublines:g=1,disabled:f=!1}={}){if(this.linkRenderer){const y=this.buildLinkRenderContext();this.linkRenderer.renderLinkDirect(e,t,n,i,s,a,r,l,d,y,{reroute:m,startControl:u,endControl:p,num_sublines:g,disabled:f})}}drawExecutionOrder(e){e.shadowColor="transparent",e.globalAlpha=.25,e.textAlign="center",e.strokeStyle="white",e.globalAlpha=.75;const{visible_nodes:t}=this;for(const n of t)e.fillStyle="black",e.fillRect(n.pos[0]-_.NODE_TITLE_HEIGHT,n.pos[1]-_.NODE_TITLE_HEIGHT,_.NODE_TITLE_HEIGHT,_.NODE_TITLE_HEIGHT),n.order==0&&e.strokeRect(n.pos[0]-_.NODE_TITLE_HEIGHT+.5,n.pos[1]-_.NODE_TITLE_HEIGHT+.5,_.NODE_TITLE_HEIGHT,_.NODE_TITLE_HEIGHT),e.fillStyle="#FFF",e.fillText($t(n.order),n.pos[0]+_.NODE_TITLE_HEIGHT*-.5,n.pos[1]-6);e.globalAlpha=1}drawNodeWidgets(e,t,n){e.drawWidgets(n,{lowQuality:this.low_quality,editorAlpha:this.getNodeModeAlpha(e)})}drawGroups(e,t){if(!this.graph)return;const n=this.graph._groups;t.save(),t.globalAlpha=.5*this.editor_alpha;const i=this.#i&&(this.isDragging||D.isDraggingVueNodes.value);for(const s of n)Le(this.visible_area,s._bounding)&&(i&&this.selectedItems.has(s)&&this.drawSnapGuide(t,s),s.draw(this,t));t.restore()}resize(e,t){if(!e&&!t){const n=this.canvas.parentElement;if(!n)throw new TypeError("Attempted to resize canvas, but parent element was null.");e=n.offsetWidth,t=n.offsetHeight}this.canvas.width==e&&this.canvas.height==t||(this.canvas.width=e??0,this.canvas.height=t??0,this.bgcanvas.width=this.canvas.width,this.bgcanvas.height=this.canvas.height,this.setDirty(!0,!0))}onNodeSelectionChange(){}boundaryNodesForSelection(){return L.getBoundaryNodes(this.selected_nodes)}showLinkMenu(e,t){const{graph:n}=this;if(!n)throw new N;const i="data"in e&&e.data!=null?e.data.constructor.name:void 0,{origin_id:s,origin_slot:a}=e;if(s==null||a==null)return new _.ContextMenu(["Link has no origin"],{event:t,title:i}),!1;const r=n.getNodeById(s),l=r?.outputs?.[a]?.type,d=new _.ContextMenu(["Add Node","Add Reroute",null,"Delete",null],{event:t,title:i,callback:u.bind(this)});return!1;function u(p,m,g){if(!n)throw new N;switch(p){case"Add Node":L.onMenuAdd(null,null,g,d,f=>{if(!f?.inputs?.length||!f?.outputs?.length||a==null)return;const y={afterRerouteId:e.parentId};r?.connectByType(a,f,l??"*",y)&&(f.pos[0]-=f.size[0]*.5)});break;case"Add Reroute":try{this.emitBeforeChange(),this.adjustMouseEvent(g),n.createReroute(e._pos,e),this.setDirty(!1,!0)}catch(f){console.error(f)}finally{this.emitAfterChange()}break;case"Delete":{const f=e instanceof J?e.linkIds.values().next().value:e.id;f!==void 0&&(n.removeLink(f),D.deleteLinkLayout(f));break}default:}}}createDefaultNodeForSlot(e){const t=Object.assign({nodeFrom:null,slotFrom:null,nodeTo:null,slotTo:null,position:[0,0],nodeType:void 0,posAdd:[0,0],posSizeFix:[0,0]},e),{afterRerouteId:n}=t,i=t.nodeFrom&&t.slotFrom!==null,s=!i&&t.nodeTo&&t.slotTo!==null;if(!i&&!s)return console.warn("No data passed to createDefaultNodeForSlot",t.nodeFrom,t.slotFrom,t.nodeTo,t.slotTo),!1;if(!t.nodeType)return console.warn("No type to createDefaultNodeForSlot"),!1;const a=i?t.nodeFrom:t.nodeTo;if(!a)throw new TypeError("nodeX was null when creating default node for slot.");let r=i?t.slotFrom:t.slotTo,l=!1;if(a instanceof _e){if(typeof r!="object"||!r)return console.warn("Cant get slot information",r),!1;const{name:p}=r;if(l=a.slots.findIndex(m=>m.name===p),r=a.slots[l],!r)return console.warn("Cant get slot information",r),!1}else switch(typeof r){case"string":l=i?a.findOutputSlot(r,!1):a.findInputSlot(r,!1),r=i?a.outputs[r]:a.inputs[r];break;case"object":if(r===null)return console.warn("Cant get slot information",r),!1;l=i?a.findOutputSlot(r.name):a.findInputSlot(r.name);break;case"number":l=r,r=i?a.outputs[r]:a.inputs[r];break;case"undefined":default:return console.warn("Cant get slot information",r),!1}const d=r.type==_.EVENT?"_event_":r.type,u=i?_.slot_types_default_out:_.slot_types_default_in;if(u?.[d]){let p=!1;if(typeof u[d]=="object"){for(const m in u[d])if(t.nodeType==u[d][m]||t.nodeType=="AUTO"){p=u[d][m];break}}else(t.nodeType==u[d]||t.nodeType=="AUTO")&&(p=u[d]);if(p){let m,g;typeof p=="object"?(m=p,g=m.node??""):g=p;const f=t.posSizeFix[0]*_.NODE_WIDTH,y=t.posSizeFix[1]*_.NODE_SLOT_HEIGHT,b=[t.position[0]+t.posAdd[0]+f,t.position[1]+t.posAdd[1]+y],v=_.createNode(g,m?.title,{pos:b});if(v){if(m){if(m.properties)for(const w in m.properties)v.addProperty(w,m.properties[w]);if(m.inputs){v.inputs=[];for(const w of m.inputs)v.addInput(w[0],w[1])}if(m.outputs){v.outputs=[];for(const w of m.outputs)v.addOutput(w[0],w[1])}m.json&&v.configure(m.json)}if(!this.graph)throw new N;this.graph.add(v);const k={node:v,opts:t};if(!this.canvas.dispatchEvent(new CustomEvent("connect-new-default-node",{detail:k,cancelable:!0})))return!0;if(i){if(!t.nodeFrom)throw new TypeError("createDefaultNodeForSlot - nodeFrom was null");t.nodeFrom.connectByType(l,v,d,{afterRerouteId:n})}else{if(!t.nodeTo)throw new TypeError("createDefaultNodeForSlot - nodeTo was null");t.nodeTo.connectByTypeOutput(l,v,d,{afterRerouteId:n})}return!0}console.error(`failed creating ${p}`)}}return!1}showConnectionMenu(e){const t=Object.assign({nodeFrom:null,slotFrom:null,nodeTo:null,slotTo:null,e:void 0,allow_searchbox:this.allow_searchbox,showSearchBox:this.showSearchBox},e||{}),n=h(()=>this.#r(),"dirty"),i=this,{graph:s}=this,{afterRerouteId:a}=t,r=t.nodeFrom&&t.slotFrom,l=!r&&t.nodeTo&&t.slotTo;if(!r&&!l){console.warn("No data passed to showConnectionMenu");return}const d=r?t.nodeFrom:t.nodeTo;if(!d)throw new TypeError("nodeX was null when creating default node for slot.");let u=r?t.slotFrom:t.slotTo,p;if(d instanceof _e){if(typeof u!="object"||!u){console.warn("Cant get slot information",u);return}const{name:v}=u;if(p=d.slots.findIndex(k=>k.name===v),p!==-1&&(u=d.slots[p]),!u){console.warn("Cant get slot information",u);return}}else switch(typeof u){case"string":p=r?d.findOutputSlot(u,!1):d.findInputSlot(u,!1),u=r?d.outputs[u]:d.inputs[u];break;case"object":if(u===null){console.warn("Cant get slot information",u);return}p=r?d.findOutputSlot(u.name):d.findInputSlot(u.name);break;case"number":p=u,u=r?d.outputs[u]:d.inputs[u];break;default:console.warn("Cant get slot information",u);return}const m=["Add Node","Add Reroute",null];t.allow_searchbox&&m.push("Search",null);const g=u.type==_.EVENT?"_event_":u.type,f=r?_.slot_types_default_out:_.slot_types_default_in;if(f?.[g])if(typeof f[g]=="object")for(const v in f[g])m.push(f[g][v]);else m.push(f[g]);const y=new _.ContextMenu(m,{event:t.e,extra:u,title:(u&&u.name!=""?u.name+(g?" | ":""):"")+(u&&g?g:""),callback:b});return y;function b(v,k,w){switch(v){case"Add Node":L.onMenuAdd(null,null,w,y,function(S){if(S)if(r){if(!t.nodeFrom)throw new TypeError("Cannot add node to SubgraphInputNode: nodeFrom was null");t.nodeFrom.connectByType(p,S,g,{afterRerouteId:a})||console.warn("Failed to make new connection.")}else{if(!t.nodeTo)throw new TypeError("Cannot add node to SubgraphInputNode: nodeTo was null");t.nodeTo.connectByTypeOutput(p,S,g,{afterRerouteId:a})}});break;case"Add Reroute":{const S=r?t.nodeFrom:t.nodeTo,E=k.extra;if(!s)throw new N;if(!S)throw new TypeError("Cannot add reroute: node was null");if(!E)throw new TypeError("Cannot add reroute: slot was null");if(!t.e)throw new TypeError("Cannot add reroute: CanvasPointerEvent was null");if(S instanceof _e)throw new TypeError("Cannot add floating reroute to Subgraph IO Nodes");if(!S.connectFloatingReroute([t.e.canvasX,t.e.canvasY],E,a))throw new Error("Failed to create reroute");n();break}case"Search":r?t.showSearchBox(w,{node_from:t.nodeFrom,slot_from:u,type_filter_in:g}):t.showSearchBox(w,{node_to:t.nodeTo,slot_from:u,type_filter_out:g});break;default:{const S={position:[t.e?.canvasX??0,t.e?.canvasY??0],nodeType:v,afterRerouteId:a},E=Object.assign(t,S);if(!i.createDefaultNodeForSlot(E))break}}}}prompt(e,t,n,i,s){const a=this;e=e||"";const r={is_modified:!1,className:"graphdialog rounded",innerHTML:s?"<span class='name'></span> <textarea autofocus class='value'></textarea><button class='rounded'>OK</button>":"<span class='name'></span> <input autofocus type='text' class='value'/><button class='rounded'>OK</button>",close(){a.prompt_box=null,d.parentNode&&d.remove()}},l=document.createElement("div"),d=Object.assign(l,r),{canvas:u}=L.active_canvas;if(!u.parentNode)throw new TypeError("canvas element parentNode was null when opening a prompt.");u.parentNode.append(d),this.ds.scale>1&&(d.style.transform=`scale(${this.ds.scale})`);let p,m=0;_.pointerListenerAdd(d,"leave",function(){m||_.dialog_close_on_mouse_leave&&!d.is_modified&&_.dialog_close_on_mouse_leave&&(p=setTimeout(d.close,_.dialog_close_on_mouse_leave_delay))}),_.pointerListenerAdd(d,"enter",function(){_.dialog_close_on_mouse_leave&&p&&clearTimeout(p)});const g=d.querySelectorAll("select");if(g)for(const E of g)E.addEventListener("click",function(){m++}),E.addEventListener("blur",function(){m=0}),E.addEventListener("change",function(){m=-1});this.prompt_box?.close(),this.prompt_box=d;const f=d.querySelector(".name");if(!f)throw new TypeError("name_element was null");f.textContent=e;const y=d.querySelector(".value");if(!y)throw new TypeError("value_element was null");y.value=String(t),y.select();const b=y;b.addEventListener("keydown",function(E){if(d.is_modified=!0,E.key=="Escape")d.close();else if(E.key=="Enter"&&E.target.localName!="textarea")n&&n(this.value),d.close();else return;E.preventDefault(),E.stopPropagation()});const v=d.querySelector("button");if(!v)throw new TypeError("button was null when opening prompt");v.addEventListener("click",function(){n?.(b.value),a.setDirty(!0),d.close()});const k=u.getBoundingClientRect();let w=-20,S=-20;return k&&(w-=k.left,S-=k.top),i?(d.style.left=`${i.clientX+w}px`,d.style.top=`${i.clientY+S}px`):(d.style.left=`${u.width*.5+w}px`,d.style.top=`${u.height*.5+S}px`),setTimeout(function(){b.focus();const E=Date.now();function C(I){I.target===u&&Date.now()-E>256&&(d.close(),u.parentElement?.removeEventListener("click",C),u.parentElement?.removeEventListener("touchend",C))}h(C,"handleOutsideClick"),u.parentElement?.addEventListener("click",C),u.parentElement?.addEventListener("touchend",C)},10),d}showSearchBox(e,t){const n={slot_from:null,node_from:null,node_to:null,do_type_filter:_.search_filter_enabled,type_filter_in:!1,type_filter_out:!1,show_general_if_none_on_typefilter:!0,show_general_after_typefiltered:!0,hide_on_mouse_leave:_.search_hide_on_mouse_leave,show_all_if_empty:!0,show_all_on_open:_.search_show_all_on_open};Object.assign(n,t);const i=this,s=L.active_canvas,{canvas:a}=s,r=a.ownerDocument||document,l=document.createElement("div"),d=Object.assign(l,{close(){i.search_box=void 0,this.blur(),a.focus(),r.body.style.overflow="",setTimeout(()=>a.focus(),20),d.remove()}});d.className="litegraph litesearchbox graphdialog rounded",d.innerHTML="<span class='name'>Search</span> <input autofocus type='text' class='value rounded'/>",n.do_type_filter&&(d.innerHTML+="<select class='slot_in_type_filter'><option value=''></option></select>",d.innerHTML+="<select class='slot_out_type_filter'><option value=''></option></select>");const u=document.createElement("div");u.className="helper",d.append(u),r.fullscreenElement?r.fullscreenElement.append(d):(r.body.append(d),r.body.style.overflow="hidden");let p,m;if(n.do_type_filter&&(p=d.querySelector(".slot_in_type_filter"),m=d.querySelector(".slot_out_type_filter")),this.ds.scale>1&&(d.style.transform=`scale(${this.ds.scale})`),n.hide_on_mouse_leave){let A=0,F=null;if(_.pointerListenerAdd(d,"enter",function(){F&&(clearTimeout(F),F=null)}),d.addEventListener("pointerleave",function(){if(A)return;const T=n.hide_on_mouse_leave,$=typeof T=="number"?T:500;F=setTimeout(d.close,$)}),n.do_type_filter){if(!p)throw new TypeError("selIn was null when showing search box");if(!m)throw new TypeError("selOut was null when showing search box");p.addEventListener("click",function(){A++}),p.addEventListener("blur",function(){A=0}),p.addEventListener("change",function(){A=-1}),m.addEventListener("click",function(){A++}),m.addEventListener("blur",function(){A=0}),m.addEventListener("change",function(){A=-1})}}i.search_box?.close(),i.search_box=d;let g=null,f=null,y=null;const b=d.querySelector("input");if(!b)throw new TypeError("Could not create search input box.");const v=b;if(v&&(v.addEventListener("blur",function(){this.focus()}),v.addEventListener("keydown",function(A){if(A.key=="ArrowUp")I(!1);else if(A.key=="ArrowDown")I(!0);else if(A.key=="Escape")d.close();else if(A.key=="Enter")y instanceof HTMLElement?C(unescape(String(y.dataset.type))):g?C(g):d.close();else{f&&clearInterval(f),f=setTimeout(P,10);return}return A.preventDefault(),A.stopPropagation(),A.stopImmediatePropagation(),!0})),n.do_type_filter){if(p){const A=_.slot_types_in,F=A.length;(n.type_filter_in==_.EVENT||n.type_filter_in==_.ACTION)&&(n.type_filter_in="_event_");for(let T=0;T<F;T++){const $=document.createElement("option");$.value=A[T],$.innerHTML=A[T],p.append($),n.type_filter_in!==!1&&String(n.type_filter_in).toLowerCase()==String(A[T]).toLowerCase()&&($.selected=!0)}p.addEventListener("change",function(){P()})}if(m){const A=_.slot_types_out;(n.type_filter_out==_.EVENT||n.type_filter_out==_.ACTION)&&(n.type_filter_out="_event_");for(const F of A){const T=document.createElement("option");T.value=F,T.innerHTML=F,m.append(T),n.type_filter_out!==!1&&String(n.type_filter_out).toLowerCase()==String(F).toLowerCase()&&(T.selected=!0)}m.addEventListener("change",function(){P()})}}const k=a.getBoundingClientRect(),w=e??new MouseEvent("click",{clientX:k.left+k.width*.5,clientY:k.top+k.height*.5,layerY:k.top+k.height*.5}),S=w.clientX-80,E=w.clientY-20;d.style.left=`${S}px`,d.style.top=`${E}px`,w.layerY>k.height-200&&(u.style.maxHeight=`${k.height-w.layerY-20}px`),requestAnimationFrame(function(){v.focus()}),n.show_all_on_open&&P();function C(A){if(A)if(i.onSearchBoxSelection)i.onSearchBoxSelection(A,w,s);else{if(!s.graph)throw new N;s.graph.beforeChange();const F=_.createNode(A);if(F&&(F.pos=s.convertEventToCanvasOffset(w),s.graph.add(F,!1)),n.node_from){let T=!1;switch(typeof n.slot_from){case"string":T=n.node_from.findOutputSlot(n.slot_from);break;case"object":if(n.slot_from==null)throw new TypeError("options.slot_from was null when showing search box");T=n.slot_from.name?n.node_from.findOutputSlot(n.slot_from.name):-1,T==-1&&n.slot_from.slot_index!==void 0&&(T=n.slot_from.slot_index);break;case"number":T=n.slot_from;break;default:T=0}if(T!==!1&&n.node_from.outputs[T]!==void 0&&T>-1){if(F==null)throw new TypeError("options.slot_from was null when showing search box");n.node_from.connectByType(T,F,n.node_from.outputs[T].type)}}if(n.node_to){let T=!1;switch(typeof n.slot_from){case"string":T=n.node_to.findInputSlot(n.slot_from);break;case"object":if(n.slot_from==null)throw new TypeError("options.slot_from was null when showing search box");T=n.slot_from.name?n.node_to.findInputSlot(n.slot_from.name):-1,T==-1&&n.slot_from.slot_index!==void 0&&(T=n.slot_from.slot_index);break;case"number":T=n.slot_from;break;default:T=0}if(T!==!1&&n.node_to.inputs[T]!==void 0&&T>-1){if(F==null)throw new TypeError("options.slot_from was null when showing search box");n.node_to.connectByTypeOutput(T,F,n.node_to.inputs[T].type)}}s.graph.afterChange()}d.close()}h(C,"select");function I(A){const F=y;y?y instanceof Element&&(y.classList.remove("selected"),y=A?y.nextSibling:y.previousSibling,y||=F):y=A?u.childNodes[0]:u.childNodes[u.childNodes.length],y instanceof Element&&(y.classList.add("selected"),y.scrollIntoView({block:"end",behavior:"smooth"}))}h(I,"changeSelection");function P(){f=null;let A=v.value;if(g=null,u.innerHTML="",!A&&!n.show_all_if_empty)return;if(i.onSearchBox){const T=i.onSearchBox(u,A,s);if(T)for(const $ of T)F($)}else{let me=function(Y,K){K=K||{};const Q=Object.assign({skipFilter:!1,inTypeOverride:!1,outTypeOverride:!1},K),ne=_.registered_node_types[Y];if($&&ne.filter!=$||(!n.show_all_if_empty||A)&&!Y.toLowerCase().includes(A)&&(!ne.title||!ne.title.toLowerCase().includes(A)))return!1;if(n.do_type_filter&&!Q.skipFilter){const Ie=Y;let he=typeof Q.inTypeOverride=="string"?Q.inTypeOverride:V?.value;if(V&&he&&_.registered_slot_in_types[he]?.nodes&&_.registered_slot_in_types[he].nodes.includes(Ie)===!1||(he=oe?.value,typeof Q.outTypeOverride=="string"&&(he=Q.outTypeOverride),oe&&he&&_.registered_slot_out_types[he]?.nodes&&_.registered_slot_out_types[he].nodes.includes(Ie)===!1))return!1}return!0};h(me,"inner_test_filter");let T=0;if(A=A.toLowerCase(),!s.graph)throw new N;const $=s.filter||s.graph.filter;let V=null,oe=null;n.do_type_filter&&i.search_box&&(V=i.search_box.querySelector(".slot_in_type_filter"),oe=i.search_box.querySelector(".slot_out_type_filter"));const x=Object.keys(_.registered_node_types).filter(Y=>me(Y));for(const Y of x)if(F(Y),L.search_limit!==-1&&T++>L.search_limit)break;if(n.show_general_after_typefiltered&&(V?.value||oe?.value)){const Y=[];for(const K in _.registered_node_types)me(K,{inTypeOverride:V&&V.value?"*":!1,outTypeOverride:oe&&oe.value?"*":!1})&&Y.push(K);for(const K of Y)if(F(K,"generic_type"),L.search_limit!==-1&&T++>L.search_limit)break}if((V?.value||oe?.value)&&u.childNodes.length==0&&n.show_general_if_none_on_typefilter){const Y=[];for(const K in _.registered_node_types)me(K,{skipFilter:!0})&&Y.push(K);for(const K of Y)if(F(K,"not_in_filter"),L.search_limit!==-1&&T++>L.search_limit)break}}function F(T,$){const V=document.createElement("div");g||=T;const oe=_.registered_node_types[T];if(oe?.title){V.textContent=oe?.title;const x=document.createElement("span");x.className="litegraph lite-search-item-type",x.textContent=T,V.append(x)}else V.textContent=T;V.dataset.type=escape(T),V.className="litegraph lite-search-item",$&&(V.className+=` ${$}`),V.addEventListener("click",function(){C(unescape(String(this.dataset.type)))}),u.append(V)}h(F,"addResult")}return h(P,"refreshHelper"),d}showEditPropertyValue(e,t,n){if(!e||e.properties[t]===void 0)return;n=n||{};const i=e.getPropertyInfo(t),{type:s}=i;let a="";if(s=="string"||s=="number"||s=="array"||s=="object")a="<input autofocus type='text' class='value'/>";else if((s=="enum"||s=="combo")&&i.values){a="<select autofocus type='text' class='value'>";for(const g in i.values){const f=Array.isArray(i.values)?i.values[g]:g,y=f==e.properties[t]?"selected":"";a+=`<option value='${f}' ${y}>${i.values[g]}</option>`}a+="</select>"}else if(s=="boolean"||s=="toggle")a=`<input autofocus type='checkbox' class='value' ${e.properties[t]?"checked":""}/>`;else{console.warn(`unknown type: ${s}`);return}const r=this.createDialog(`<span class='name'>${i.label||t}</span>${a}<button>OK</button>`,n);let l;if((s=="enum"||s=="combo")&&i.values)l=r.querySelector("select"),l?.addEventListener("change",function(g){r.modified(),m(g.target?.value)});else if(s=="boolean"||s=="toggle")l=r.querySelector("input"),l?.addEventListener("click",function(){r.modified(),m(!!l.checked)});else if(l=r.querySelector("input"),l){l.addEventListener("blur",function(){this.focus()});let g=e.properties[t]!==void 0?e.properties[t]:"";s!=="string"&&(g=JSON.stringify(g)),l.value=g,l.addEventListener("keydown",function(f){if(f.key=="Escape")r.close();else if(f.key=="Enter")u();else{r.modified();return}f.preventDefault(),f.stopPropagation()})}l?.focus();const d=r.querySelector("button");if(!d)throw new TypeError("Show edit property value button was null.");d.addEventListener("click",u);function u(){m(l?.value)}h(u,"inner");const p=h(()=>this.#r(),"dirty");function m(g){i?.values&&typeof i.values=="object"&&i.values[g]!=null&&(g=i.values[g]),typeof e.properties[t]=="number"&&(g=Number(g)),(s=="array"||s=="object")&&(g=JSON.parse(g)),e.properties[t]=g,e.graph&&e.graph._version++,e.onPropertyChanged?.(t,g),n.onclose?.(),r.close(),p()}return h(m,"setValue"),r}createDialog(e,t){t=Object.assign({checkForInput:!1,closeOnLeave:!0,closeOnLeave_checkModified:!0},t||{});const n={className:"graphdialog",innerHTML:e,is_modified:!1,modified(){this.is_modified=!0},close(){this.remove()}},i=document.createElement("div"),s=Object.assign(i,n),a=this.canvas.getBoundingClientRect();let r=-20,l=-20;if(a&&(r-=a.left,l-=a.top),t.position?(r+=t.position[0],l+=t.position[1]):t.event?(r+=t.event.clientX,l+=t.event.clientY):(r+=this.canvas.width*.5,l+=this.canvas.height*.5),s.style.left=`${r}px`,s.style.top=`${l}px`,!this.canvas.parentNode)throw new TypeError("Canvas parent element was null.");if(this.canvas.parentNode.append(s),t.checkForInput){const m=s.querySelectorAll("input");if(m)for(const g of m)g.addEventListener("keydown",function(f){if(s.modified(),f.key=="Escape")s.close();else if(f.key!="Enter")return;f.preventDefault(),f.stopPropagation()}),g.focus()}let d,u=0;s.addEventListener("mouseleave",function(){u||!s.is_modified&&_.dialog_close_on_mouse_leave&&(d=setTimeout(s.close,_.dialog_close_on_mouse_leave_delay))}),s.addEventListener("mouseenter",function(){(t.closeOnLeave||_.dialog_close_on_mouse_leave)&&d&&clearTimeout(d)});const p=s.querySelectorAll("select");if(p)for(const m of p)m.addEventListener("click",function(){u++}),m.addEventListener("blur",function(){u=0}),m.addEventListener("change",function(){u=-1});return s}createPanel(e,t){t=t||{};const n=document.createElement("div");if(n.className="litegraph dialog",n.innerHTML="<div class='dialog-header'><span class='dialog-title'></span></div><div class='dialog-content'></div><div style='display:none;' class='dialog-alt-content'></div><div class='dialog-footer'></div>",n.header=n.querySelector(".dialog-header"),t.width&&(n.style.width=t.width+(typeof t.width=="number"?"px":"")),t.height&&(n.style.height=t.height+(typeof t.height=="number"?"px":"")),t.closable){const i=document.createElement("span");i.innerHTML="✕",i.classList.add("close"),i.addEventListener("click",function(){n.close()}),n.header.append(i)}return n.title_element=n.querySelector(".dialog-title"),n.title_element.textContent=e,n.content=n.querySelector(".dialog-content"),n.alt_content=n.querySelector(".dialog-alt-content"),n.footer=n.querySelector(".dialog-footer"),n.footer.style.marginTop="-96px",n.close=function(){typeof n.onClose=="function"&&n.onClose(),n.remove(),this.remove()},n.toggleAltContent=function(i){let s,a;i!==void 0?(s=i?"block":"none",a=i?"none":"block"):(s=n.alt_content.style.display!="block"?"block":"none",a=n.alt_content.style.display!="block"?"none":"block"),n.alt_content.style.display=s,n.content.style.display=a},n.toggleFooterVisibility=function(i){let s;i!==void 0?s=i?"block":"none":s=n.footer.style.display!="block"?"block":"none",n.footer.style.display=s},n.clear=function(){this.content.innerHTML=""},n.addHTML=function(i,s,a){const r=document.createElement("div");return s&&(r.className=s),r.innerHTML=i,a?n.footer.append(r):n.content.append(r),r},n.addButton=function(i,s,a){const r=document.createElement("button");return r.textContent=i,r.options=a,r.classList.add("btn"),r.addEventListener("click",s),n.footer.append(r),r},n.addSeparator=function(){const i=document.createElement("div");i.className="separator",n.content.append(i)},n.addWidget=function(i,s,a,r,l){r=r||{};let d=String(a);i=i.toLowerCase(),i=="number"&&typeof a=="number"&&(d=a.toFixed(3));const u=document.createElement("div");u.className="property",u.innerHTML="<span class='property_name'></span><span class='property_value'></span>";const p=u.querySelector(".property_name");if(!p)throw new TypeError("Property name element was null.");p.textContent=r.label||s;const m=u.querySelector(".property_value");if(!m)throw new TypeError("Property name element was null.");if(m.textContent=d,u.dataset.property=s,u.dataset.type=r.type||i,u.options=r,u.value=a,i=="code")u.addEventListener("click",function(){const f=this.dataset.property;f&&n.inner_showCodePad?.(f)});else if(i=="boolean")u.classList.add("boolean"),a&&u.classList.add("bool-on"),u.addEventListener("click",()=>{const f=u.dataset.property;if(u.value=!u.value,u.classList.toggle("bool-on"),!m)throw new TypeError("Property name element was null.");m.textContent=u.value?"true":"false",g(f,u.value)});else if(i=="string"||i=="number"){if(!m)throw new TypeError("Property name element was null.");m.setAttribute("contenteditable","true"),m.addEventListener("keydown",function(f){f.code=="Enter"&&(i!="string"||!f.shiftKey)&&(f.preventDefault(),this.blur())}),m.addEventListener("blur",function(){let f=this.textContent;const y=this.parentElement?.dataset.property;this.parentElement?.dataset.type=="number"&&(f=Number(f)),g(y,f)})}else if(i=="enum"||i=="combo"){const f=L.getPropertyPrintableValue(a,r.values);if(!m)throw new TypeError("Property name element was null.");m.textContent=f??"",m.addEventListener("click",function(y){const b=r?.values||[],v=this.parentElement?.dataset.property,k=h(w=>(this.textContent=w??null,g(v,w),!1),"inner_clicked");new _.ContextMenu(b,{event:y,className:"dark",callback:k})})}n.content.append(u);function g(f,y){const b=r||{};b.callback?.(f,y,b),l?.(f,y,b)}return h(g,"innerChange"),u},typeof n.onOpen=="function"&&n.onOpen(),n}closePanels(){document.querySelector("#node-panel")?.close?.(),document.querySelector("#option-panel")?.close?.()}showShowNodePanel(e){this.SELECTED_NODE=e,this.closePanels();const t=this.getCanvasWindow(),n=this.createPanel(e.title||"",{closable:!0,window:t,onOpen:h(()=>{this.NODEPANEL_IS_OPEN=!0},"onOpen"),onClose:h(()=>{this.NODEPANEL_IS_OPEN=!1,this.node_panel=void 0},"onClose")});this.node_panel=n,n.id="node-panel",n.node=e,n.classList.add("settings"),n.style.position="absolute",n.style.top="96px",n.style.left="65px";const i=h(()=>{n.content.innerHTML="",n.addHTML(`<span class='node_type'>${e.type}</span><span class='node_desc'>${e.constructor.desc||""}</span><span class='separator'></span>`),n.addHTML("<h3>Properties</h3>");const s=h((l,d)=>{if(!this.graph)throw new N;if(l){switch(this.graph.beforeChange(e),l){case"Title":if(typeof d!="string")throw new TypeError("Attempting to set title to non-string value.");e.title=d;break;case"Mode":{if(typeof d!="string")throw new TypeError("Attempting to set mode to non-string value.");const u=Object.values(_.NODE_MODES).indexOf(d);u!==-1&&_.NODE_MODES[u]?e.changeMode(u):console.warn(`unexpected mode: ${d}`);break}case"Color":if(typeof d!="string")throw new TypeError("Attempting to set colour to non-string value.");L.node_colors[d]?(e.color=L.node_colors[d].color,e.bgcolor=L.node_colors[d].bgcolor):console.warn(`unexpected color: ${d}`);break;default:e.setProperty(l,d);break}this.graph.afterChange(),this.dirty_canvas=!0}},"fUpdate");n.addWidget("string","Title",e.title,{},s);const a=e.mode==null?void 0:_.NODE_MODES[e.mode];n.addWidget("combo","Mode",a,{values:_.NODE_MODES},s);const r=e.color!==void 0?Object.keys(L.node_colors).filter(function(l){return L.node_colors[l].color==e.color}):"";n.addWidget("combo","Color",r,{values:Object.keys(L.node_colors)},s);for(const l in e.properties){const d=e.properties[l],u=e.getPropertyInfo(l);e.onAddPropertyToPanel?.(l,n)||n.addWidget(u.widget||u.type,l,d,u,s)}n.addSeparator(),e.onShowCustomPanelInfo?.(n),n.footer.innerHTML="",n.addButton("Delete",function(){if(!e.block_delete){if(!e.graph)throw new N;e.graph.remove(e),n.close()}}).classList.add("delete")},"inner_refresh");if(n.inner_showCodePad=function(s){n.classList.remove("settings"),n.classList.add("centered"),n.alt_content.innerHTML="<textarea class='code'></textarea>";const a=n.alt_content.querySelector("textarea"),r=h(function(){n.toggleAltContent(!1),n.toggleFooterVisibility(!0),a.remove(),n.classList.add("settings"),n.classList.remove("centered"),i()},"fDoneWith");a.value=String(e.properties[s]),a.addEventListener("keydown",function(u){u.code=="Enter"&&u.ctrlKey&&(e.setProperty(s,a.value),r())}),n.toggleAltContent(!0),n.toggleFooterVisibility(!1),a.style.height="calc(100% - 40px)";const l=n.addButton("Assign",function(){e.setProperty(s,a.value),r()});n.alt_content.append(l);const d=n.addButton("Close",r);d.style.float="right",n.alt_content.append(d)},i(),!this.canvas.parentNode)throw new TypeError("showNodePanel - this.canvas.parentNode was null");this.canvas.parentNode.append(n)}checkPanels(){if(!this.canvas)return;if(!this.canvas.parentNode)throw new TypeError("checkPanels - this.canvas.parentNode was null");const e=this.canvas.parentNode.querySelectorAll(".litegraph.dialog");for(const t of e)t.node&&(!t.node.graph||t.graph!=this.graph)&&t.close()}getCanvasMenuOptions(){let e;this.getMenuOptions?e=this.getMenuOptions():(e=[{content:"Add Node",has_submenu:!0,callback:L.onMenuAdd},{content:"Add Group",callback:L.onGroupAdd},{content:"Paste",callback:h(()=>{this.pasteFromClipboard()},"callback")}],Object.keys(this.selected_nodes).length>1&&e.push({content:"Convert to Subgraph",callback:h(()=>{if(!this.selectedItems.size)throw new Error("Convert to Subgraph: Nothing selected.");this._graph.convertToSubgraph(this.selectedItems)},"callback")},{content:"Align",has_submenu:!0,callback:L.onGroupAlign}));const t=this.getExtraMenuOptions?.(this,e);return Array.isArray(t)?e.concat(t):e}getNodeMenuOptions(e){let t;e.getMenuOptions?t=e.getMenuOptions(this):(t=[{content:"Convert to Subgraph",callback:h(()=>{if(this.selectedItems.size){let i=!1;for(const s of this.selectedItems){const a=s;if(typeof a.type=="string"&&a.type.startsWith("workflow>")&&a.convertToNodes){i=!0;const r=a.convertToNodes();requestAnimationFrame(()=>{if(this.selectItems(r,!0),!this.selectedItems.size)throw new Error("Convert to Subgraph: Nothing selected.");this._graph.convertToSubgraph(this.selectedItems)});return}}if(!i){if(!this.selectedItems.size)throw new Error("Convert to Subgraph: Nothing selected.");this._graph.convertToSubgraph(this.selectedItems)}}else throw new Error("Convert to Subgraph: Nothing selected.")},"callback")},{content:"Properties",has_submenu:!0,callback:L.onShowMenuNodeProperties},{content:"Properties Panel",callback:h(function(i,s,a,r,l){L.active_canvas.showShowNodePanel(l)},"callback")},null,{content:"Title",callback:L.onShowPropertyEditor},{content:"Mode",has_submenu:!0,callback:L.onMenuNodeMode}],e.resizable!==!1&&t.push({content:"Resize",callback:L.onMenuResizeNode}),e.collapsible&&t.push({content:e.collapsed?"Expand":"Collapse",callback:L.onMenuNodeCollapse}),e.widgets?.some(i=>i.advanced)&&t.push({content:e.showAdvanced?"Hide Advanced":"Show Advanced",callback:L.onMenuToggleAdvanced}),t.push({content:e.pinned?"Unpin":"Pin",callback:h(()=>{for(const i in this.selected_nodes)this.selected_nodes[i].pin();this.setDirty(!0,!0)},"callback")},{content:"Colors",has_submenu:!0,callback:L.onMenuNodeColors},{content:"Shapes",has_submenu:!0,callback:L.onMenuNodeShapes},null));const n=e.getExtraMenuOptions?.(this,t);return Array.isArray(n)&&n.length>0&&(n.push(null),t=n.concat(t)),e.clonable!==!1&&t.push({content:"Clone",callback:L.onMenuNodeClone}),Object.keys(this.selected_nodes).length>1&&t.push({content:"Align Selected To",has_submenu:!0,callback:L.onNodeAlign},{content:"Distribute Nodes",has_submenu:!0,callback:L.createDistributeMenu}),t.push(null,{content:"Remove",disabled:!(e.removable!==!1&&!e.block_delete),callback:L.onMenuNodeRemove}),e.graph?.onGetNodeMenuOptions?.(t,e),t}getGroupMenuOptions(e){return console.warn("LGraphCanvas.getGroupMenuOptions is deprecated, use LGraphGroup.getMenuOptions instead"),e.getMenuOptions()}processContextMenu(e,t){let n;const i={event:t,callback:r,extra:e};if(e){i.title=e.displayType??e.type??void 0,L.active_node=e;const l=e.getSlotInPosition(t.canvasX,t.canvasY);if(l){if(n=[],e.getSlotMenuOptions)n=e.getSlotMenuOptions(l);else{(l.output?.links?.length||l.input?.link!=null)&&n.push({content:"Disconnect Links",slot:l});const d=l.input||l.output;if(!d)throw new TypeError("Both in put and output slots were null when processing context menu.");!d.nameLocked&&!("link"in d&&d.widget)&&n.push({content:"Rename Slot",slot:l}),d.removable&&(n.push(null),n.push(d.locked?"Cannot remove":{content:"Remove Slot",slot:l,className:"danger"})),e.getExtraSlotMenuOptions&&n.push(...e.getExtraSlotMenuOptions(l))}i.title=(l.input?l.input.type:l.output.type)||"*",l.input&&l.input.type==_.ACTION&&(i.title="Action"),l.output&&l.output.type==_.EVENT&&(i.title="Event")}else n=this.getNodeMenuOptions(e)}else{if(n=this.getCanvasMenuOptions(),!this.graph)throw new N;if(this.links_render_mode!==ie.HIDDEN_LINK){const d=D.queryRerouteAtPoint({x:t.canvasX,y:t.canvasY});let u;d?u=this.graph.getReroute(d.id):u=this.graph.getRerouteOnPos(t.canvasX,t.canvasY,this.#s),u&&n.unshift({content:"Delete Reroute",callback:h(()=>{if(!this.graph)throw new N;this.graph.removeReroute(u.id)},"callback")},null)}const l=this.graph.getGroupOnPos(t.canvasX,t.canvasY);l&&n.push(null,{content:"Edit Group",has_submenu:!0,submenu:{title:"Group",extra:l,options:l.getMenuOptions()}})}if(!n)return;new _.ContextMenu(n,i);const s=h(l=>this.createDialog("<span class='name'>Name</span><input autofocus type='text'/><button>OK</button>",l),"createDialog"),a=h(()=>this.setDirty(!0),"setDirty");function r(l,d){if(l){if(l.content=="Remove Slot"){if(!e?.graph)throw new N;const u=l.slot;if(!u)throw new TypeError("Found-slot info was null when processing context menu.");e.graph.beforeChange(),u.input?e.removeInput(u.slot):u.output&&e.removeOutput(u.slot),e.graph.afterChange();return}else if(l.content=="Disconnect Links"){if(!e?.graph)throw new N;const u=l.slot;if(!u)throw new TypeError("Found-slot info was null when processing context menu.");e.graph.beforeChange(),u.output?e.disconnectOutput(u.slot):u.input&&e.disconnectInput(u.slot,!0),e.graph.afterChange();return}else if(l.content=="Rename Slot"){if(!e)throw new TypeError("`node` was null when processing the context menu.");const u=l.slot;if(!u)throw new TypeError("Found-slot info was null when processing context menu.");const p=u.input?e.getInputInfo(u.slot):e.getOutputInfo(u.slot),m=s(d),g=m.querySelector("input");g&&p&&(g.value=p.label||"");const f=h(function(){if(!e.graph)throw new N;e.graph.beforeChange(),g?.value&&(p&&(p.label=g.value),a()),m.close(),e.graph.afterChange()},"inner");if(m.querySelector("button")?.addEventListener("click",f),!g)throw new TypeError("Input element was null when processing context menu.");g.addEventListener("keydown",function(y){if(m.is_modified=!0,y.key=="Escape")m.close();else if(y.key=="Enter")f();else if(y.target.localName!="textarea")return;y.preventDefault(),y.stopPropagation()}),g.focus()}}}h(r,"inner_option_clicked")}animateToBounds(e,t={}){const n=h(()=>this.setDirty(!0,!0),"setDirty");this.ds.animateToBounds(e,n,t)}fitViewToSelectionAnimated(e={}){const t=et(this.selectedItems.size?Array.from(this.selectedItems):this.positionableItems);if(!t)throw new TypeError("Attempted to fit to view but could not calculate bounds.");const n=h(()=>this.setDirty(!0,!0),"setDirty");this.ds.animateToBounds(t,n,e)}calculateNewPosition(e,t,n){return{x:e.pos[0]+t,y:e.pos[1]+n}}applyNodePositionUpdates(e,t){for(const{node:n,newPos:i}of e)n.pos[0]=i.x,n.pos[1]=i.y,t.moveNode(n.id,i)}initLayoutMutations(){const e=Ae();return e.setSource(ue.Canvas),e}collectNodesInGroups(e){const t=new Set;for(const n of e)if(n instanceof de)for(const i of n._children)i instanceof q&&t.add(i);return t}moveGroupChildren(e,t,n,i){for(const s of e._children)if(s instanceof q){const a=s;i.push({node:a,newPos:this.calculateNewPosition(a,t,n)})}else s instanceof de||s.move(t,n,!0)}moveChildNodesInGroupVueMode(e,t,n){const i=this.initLayoutMutations(),s=this.collectNodesInGroups(e),a=[];for(const r of e)if(r instanceof q){const l=r;if(s.has(l))continue;a.push({node:l,newPos:this.calculateNewPosition(l,t,n)})}else r instanceof de?(r.move(t,n,!0),this.moveGroupChildren(r,t,n,a)):r.move(t,n,!0);this.applyNodePositionUpdates(a,i)}repositionNodesVueMode(e){const t=this.initLayoutMutations();this.applyNodePositionUpdates(e,t)}},Mo=class{static{h(this,"MapProxyHandler")}getOwnPropertyDescriptor(o,e){const t=this.get(o,e);if(t)return{configurable:!0,enumerable:!0,value:t}}has(o,e){if(typeof e=="symbol")return!1;const t=parseInt(e,10);return o.has(isNaN(t)?e:t)}ownKeys(o){return[...o.keys()].map(String)}get(o,e){if(e in o)return Reflect.get(o,e,o);if(typeof e=="symbol")return;const t=parseInt(e,10);return o.get(isNaN(t)?e:t)}set(o,e,t){if(typeof e=="symbol")return!1;const n=parseInt(e,10);return o.set(isNaN(n)?e:n,t),!0}deleteProperty(o,e){return o.delete(e)}static bindAllMethods(o){o.clear=o.clear.bind(o),o.delete=o.delete.bind(o),o.forEach=o.forEach.bind(o),o.get=o.get.bind(o),o.has=o.has.bind(o),o.set=o.set.bind(o),o.entries=o.entries.bind(o),o.keys=o.keys.bind(o),o.values=o.values.bind(o),o[Symbol.iterator]=o[Symbol.iterator].bind(o)}},Zt=class ge{static{h(this,"LGraph")}static serialisedSchemaVersion=1;static STATUS_STOPPED=1;static STATUS_RUNNING=2;static ConfigureProperties=new Set(["nodes","groups","links","state","reroutes","floatingLinks","id","subgraphs","definitions","inputs","outputs","widgets","inputNode","outputNode","extra"]);id=bt;revision=0;_version=-1;_links=new Map;links;list_of_graphcanvas;status=ge.STATUS_STOPPED;state={lastGroupId:0,lastNodeId:0,lastLinkId:0,lastRerouteId:0};events=new Et;_subgraphs=new Map;_nodes=[];_nodes_by_id={};_nodes_in_order=[];_nodes_executable=null;_groups=[];iteration=0;globaltime=0;runningtime=0;fixedtime=0;fixedtime_lapse=.01;elapsed_time=.01;last_update_time=0;starttime=0;catch_errors=!0;execution_timer_id;errors_in_execution;execution_time;_last_trigger_time;filter;config={};vars={};nodes_executing=[];nodes_actioning=[];nodes_executedAction=[];extra={};version;get empty(){return this._nodes.length+this._groups.length+this.reroutes.size===0}*positionableItems(){for(const e of this._nodes)yield e;for(const e of this._groups)yield e;for(const e of this.reroutes.values())yield e}#e=0;floatingLinksInternal=new Map;get floatingLinks(){return this.floatingLinksInternal}reroutesInternal=new Map;get reroutes(){return this.reroutesInternal}get rootGraph(){return this}get isRootGraph(){return this.rootGraph===this}get last_node_id(){return this.state.lastNodeId}set last_node_id(e){this.state.lastNodeId=e}get last_link_id(){return this.state.lastLinkId}set last_link_id(e){this.state.lastLinkId=e}onTrigger;_input_nodes;constructor(e){const t=this._links;Mo.bindAllMethods(t);const n=new Mo;this.links=new Proxy(t,n),this.list_of_graphcanvas=null,this.clear(),e&&this.configure(e)}clear(){if(this.stop(),this.status=ge.STATUS_STOPPED,this.id=bt,this.revision=0,this.state={lastGroupId:0,lastNodeId:0,lastLinkId:0,lastRerouteId:0},this._version=-1,this._subgraphs.clear(),this._nodes)for(const e of this._nodes)e.onRemoved?.(),this.onNodeRemoved?.(e);this._nodes=[],this._nodes_by_id={},this._nodes_in_order=[],this._nodes_executable=null,this._links.clear(),this.reroutes.clear(),this.floatingLinksInternal.clear(),this.#e=0,this._groups=[],this.iteration=0,this.config={},this.vars={},this.extra={},this.globaltime=0,this.runningtime=0,this.fixedtime=0,this.fixedtime_lapse=.01,this.elapsed_time=.01,this.last_update_time=0,this.starttime=0,this.catch_errors=!0,this.nodes_executing=[],this.nodes_actioning=[],this.nodes_executedAction=[],this.change(),this.canvasAction(e=>e.clear())}get subgraphs(){return this.rootGraph._subgraphs}get nodes(){return this._nodes}get groups(){return this._groups}attachCanvas(e){if(!(e instanceof ce))throw new TypeError("attachCanvas expects an LGraphCanvas instance");this.primaryCanvas=e,this.list_of_graphcanvas??=[],this.list_of_graphcanvas.includes(e)||this.list_of_graphcanvas.push(e),e.graph!==this&&(e.graph?.detachCanvas(e),e.graph=this,e.subgraph=void 0)}detachCanvas(e){e.graph=null;const t=this.list_of_graphcanvas;if(t){const n=t.indexOf(e);n!==-1&&t.splice(n,1)}}start(e){if(this.status!=ge.STATUS_RUNNING)if(this.status=ge.STATUS_RUNNING,this.onPlayEvent?.(),this.sendEventToAllNodes("onStart"),this.starttime=_.getTime(),this.last_update_time=this.starttime,e||=0,e==0&&typeof window<"u"&&window.requestAnimationFrame){const t=h(()=>{this.execution_timer_id==-1&&(window.requestAnimationFrame(t),this.onBeforeStep?.(),this.runStep(1,!this.catch_errors),this.onAfterStep?.())},"on_frame");this.execution_timer_id=-1,t()}else this.execution_timer_id=setInterval(()=>{this.onBeforeStep?.(),this.runStep(1,!this.catch_errors),this.onAfterStep?.()},e)}stop(){this.status!=ge.STATUS_STOPPED&&(this.status=ge.STATUS_STOPPED,this.onStopEvent?.(),this.execution_timer_id!=null&&(this.execution_timer_id!=-1&&clearInterval(this.execution_timer_id),this.execution_timer_id=null),this.sendEventToAllNodes("onStop"))}runStep(e,t,n){e=e||1;const i=_.getTime();this.globaltime=.001*(i-this.starttime);const s=this._nodes_executable||this._nodes;if(!s)return;if(n=n||s.length,t){for(let l=0;l<e;l++){for(let d=0;d<n;++d){const u=s[d];u.mode==H.ALWAYS&&u.onExecute&&u.doExecute?.()}this.fixedtime+=this.fixedtime_lapse,this.onExecuteStep?.()}this.onAfterExecute?.()}else try{for(let l=0;l<e;l++){for(let d=0;d<n;++d){const u=s[d];u.mode==H.ALWAYS&&u.onExecute?.()}this.fixedtime+=this.fixedtime_lapse,this.onExecuteStep?.()}this.onAfterExecute?.(),this.errors_in_execution=!1}catch(l){if(this.errors_in_execution=!0,_.throw_errors)throw l;_.debug&&console.error("Error during execution:",l),this.stop()}const a=_.getTime();let r=a-i;r==0&&(r=1),this.execution_time=.001*r,this.globaltime+=.001*r,this.iteration+=1,this.elapsed_time=(a-this.last_update_time)*.001,this.last_update_time=a,this.nodes_executing=[],this.nodes_actioning=[],this.nodes_executedAction=[]}updateExecutionOrder(){this._nodes_in_order=this.computeExecutionOrder(!1),this._nodes_executable=[];for(const e of this._nodes_in_order)e.onExecute&&this._nodes_executable.push(e)}computeExecutionOrder(e,t){const n=[],i=[],s={},a={},r={};for(const d of this._nodes){if(e&&!d.onExecute)continue;s[d.id]=d;let u=0;if(d.inputs)for(const p of d.inputs)p?.link!=null&&(u+=1);u==0?(i.push(d),t&&(d._level=1)):(t&&(d._level=0),r[d.id]=u)}for(;;){const d=i.shift();if(d===void 0)break;if(n.push(d),delete s[d.id],!!d.outputs){for(const u of d.outputs)if(!(u?.links==null||u.links.length==0))for(const p of u.links){const m=this._links.get(p);if(!m||a[m.id])continue;const g=this.getNodeById(m.target_id);if(g==null){a[m.id]=!0;continue}t&&(d._level??=0,(!g._level||g._level<=d._level)&&(g._level=d._level+1)),a[m.id]=!0,r[g.id]-=1,r[g.id]==0&&i.push(g)}}}for(const d in s)n.push(s[d]);n.length!=this._nodes.length&&_.debug&&console.warn("something went wrong, nodes missing");function l(d){const u=d.length;for(let p=0;p<u;++p)d[p].order=p}return h(l,"setOrder"),l(n),n.sort(function(d,u){const p=d.constructor.priority||d.priority||0,m=u.constructor.priority||u.priority||0;return p==m?d.order-u.order:p-m}),l(n),n}arrange(e,t){e=e||100;const n=this.computeExecutionOrder(!1,!0),i=[];for(const a of n){const r=a._level||1;i[r]||=[],i[r].push(a)}let s=e;for(const a of i){if(!a)continue;let r=100,l=e+_.NODE_TITLE_HEIGHT;for(const d of a){d.pos[0]=t==_.VERTICAL_LAYOUT?l:s,d.pos[1]=t==_.VERTICAL_LAYOUT?s:l;const u=t==_.VERTICAL_LAYOUT?1:0;d.size[u]>r&&(r=d.size[u]);const p=t==_.VERTICAL_LAYOUT?0:1;l+=d.size[p]+e+_.NODE_TITLE_HEIGHT}s+=r+e}this.setDirtyCanvas(!0,!0)}getTime(){return this.globaltime}getFixedTime(){return this.fixedtime}getElapsedTime(){return this.elapsed_time}sendEventToAllNodes(e,t,n){n=n||H.ALWAYS;const i=this._nodes_in_order||this._nodes;if(i)for(const s of i)!s[e]||s.mode!=n||(t===void 0?s[e]():t&&t.constructor===Array?s[e].apply(s,t):s[e](t))}canvasAction(e){const t=this.list_of_graphcanvas;if(t)for(const n of t)e(n)}sendActionToCanvas(e,t){const{list_of_graphcanvas:n}=this;if(n)for(const i of n){const s=i[e];if(typeof s=="function"){const a=t==null?[]:Array.isArray(t)?t:[t];s.apply(i,a)}}}add(e,t){if(!e)return;const{state:n}=this;if(_.alwaysSnapToGrid){const i=this.getSnapToGridSize();i&&e.snapToGrid(i)}if(e instanceof de){(e.id==null||e.id===-1)&&(e.id=++n.lastGroupId),e.id>n.lastGroupId&&(n.lastGroupId=e.id),this._groups.push(e),this.setDirtyCanvas(!0),this.change(),e.graph=this,this._version++;return}if(e.id!=-1&&this._nodes_by_id[e.id]!=null&&(console.warn("LiteGraph: there is already a node with this ID, changing it"),e.id=_.use_uuids?_.uuidv4():++n.lastNodeId),this._nodes.length>=_.MAX_NUMBER_OF_NODES)throw"LiteGraph: max number of nodes in a graph reached";return _.use_uuids?(e.id==null||e.id==-1)&&(e.id=_.uuidv4()):e.id==null||e.id==-1?e.id=++n.lastNodeId:typeof e.id=="number"&&n.lastNodeId<e.id&&(n.lastNodeId=e.id),e.graph=this,this._version++,this._nodes.push(e),this._nodes_by_id[e.id]=e,e.onAdded?.(this),this.config.align_to_grid&&e.alignToGrid(),t||this.updateExecutionOrder(),this.onNodeAdded?.(e),this.setDirtyCanvas(!0),this.change(),e}remove(e){if(e instanceof de){this.canvasAction(r=>r.deselect(e));const a=this._groups.indexOf(e);a!=-1&&this._groups.splice(a,1),e.graph=void 0,this._version++,this.setDirtyCanvas(!0,!0),this.change();return}if(this._nodes_by_id[e.id]==null){console.warn("LiteGraph: node not found",e);return}if(e.ignore_remove){console.warn("LiteGraph: node cannot be removed",e);return}this.beforeChange();const{inputs:t,outputs:n}=e;if(t)for(const[a,r]of t.entries())r.link!=null&&e.disconnectInput(a,!0);if(n)for(const[a,r]of n.entries())r.links?.length&&e.disconnectOutput(a);for(const a of this.floatingLinks.values())(a.origin_id===e.id||a.target_id===e.id)&&this.removeFloatingLink(a);e.onRemoved?.(),e.graph=null,this._version++;const{list_of_graphcanvas:i}=this;if(i)for(const a of i)a.selected_nodes[e.id]&&delete a.selected_nodes[e.id],a.deselect(e);const s=this._nodes.indexOf(e);s!=-1&&this._nodes.splice(s,1),delete this._nodes_by_id[e.id],this.onNodeRemoved?.(e),this.canvasAction(a=>a.checkPanels()),this.setDirtyCanvas(!0,!0),this.afterChange(),this.change(),this.updateExecutionOrder()}getNodeById(e){return e!=null?this._nodes_by_id[e]:null}findNodesByClass(e,t){t=t||[],t.length=0;const{_nodes:n}=this;for(const i of n)i.constructor===e&&t.push(i);return t}findNodesByType(e,t){const n=e.toLowerCase();t=t||[],t.length=0;const{_nodes:i}=this;for(const s of i)s.type?.toLowerCase()==n&&t.push(s);return t}findNodeByTitle(e){const{_nodes:t}=this;for(const n of t)if(n.title==e)return n;return null}findNodesByTitle(e){const t=[],{_nodes:n}=this;for(const i of n)i.title==e&&t.push(i);return t}getNodeOnPos(e,t,n){const i=n||this._nodes;let s=i.length;for(;--s>=0;){const a=i[s];if(a.isPointInside(e,t))return a}return null}getGroupOnPos(e,t){for(let n=this._groups.length-1;n>=0;n--){const i=this._groups[n];if(i.isPointInside(e,t))return i}}getGroupTitlebarOnPos(e,t){for(let n=this._groups.length-1;n>=0;n--){const i=this._groups[n];if(i.isPointInTitlebar(e,t))return i}}getRerouteOnPos(e,t,n){for(const i of n??this.reroutes.values())if(i.containsPoint([e,t]))return i}snapToGrid(e){const t=this.getSnapToGridSize();if(t)for(const n of yn(e))n.pinned||n.snapToGrid(t)}getSnapToGridSize(){return _.alwaysSnapToGrid?_.CANVAS_GRID_SIZE||1:_.CANVAS_GRID_SIZE}checkNodeTypes(){const{_nodes:e}=this;for(const[t,n]of e.entries()){const i=_.registered_node_types[n.type];if(n.constructor==i)continue;console.warn("node being replaced by newer version:",n.type);const s=_.createNode(n.type);s&&(e[t]=s,s.configure(n.serialize()),s.graph=this,this._nodes_by_id[s.id]=s,n.inputs&&(s.inputs=[...n.inputs]),n.outputs&&(s.outputs=[...n.outputs]))}this.updateExecutionOrder()}trigger(e,t){new Set(["node:slot-links:changed","node:slot-errors:changed","node:property:changed"]).has(e)&&t&&typeof t=="object"&&this.onTrigger?.({type:e,...t})}triggerInput(e,t){const n=this.findNodesByTitle(e);for(const i of n)i.onTrigger(t)}setCallback(e,t){const n=this.findNodesByTitle(e);for(const i of n)i.setTrigger(t)}beforeChange(e){this.onBeforeChange?.(this,e),this.canvasAction(t=>t.onBeforeChange?.(this))}afterChange(e){this.onAfterChange?.(this,e),this.canvasAction(t=>t.onAfterChange?.(this))}clearTriggeredSlots(){for(const e of this._links.values())e&&e._last_time&&(e._last_time=0)}change(){this.canvasAction(e=>e.setDirty(!0,!0)),this.on_change?.(this)}setDirtyCanvas(e,t){this.canvasAction(n=>n.setDirty(e,t))}addFloatingLink(e){e.id===-1&&(e.id=++this.#e),this.floatingLinksInternal.set(e.id,e);const t=e.target_id!==-1?this.getNodeById(e.target_id)?.inputs?.[e.target_slot]:this.getNodeById(e.origin_id)?.outputs?.[e.origin_slot];t?(t._floatingLinks??=new Set,t._floatingLinks.add(e)):console.warn(`Adding invalid floating link: target/slot: [${e.target_id}/${e.target_slot}] origin/slot: [${e.origin_id}/${e.origin_slot}]`);const n=z.getReroutes(this,e);for(const i of n)i.floatingLinkIds.add(e.id);return e}removeFloatingLink(e){this.floatingLinksInternal.delete(e.id);const t=e.target_id!==-1?this.getNodeById(e.target_id)?.inputs?.[e.target_slot]:this.getNodeById(e.origin_id)?.outputs?.[e.origin_slot];t&&t._floatingLinks?.delete(e);const n=z.getReroutes(this,e);for(const i of n)i.floatingLinkIds.delete(e.id),i.floatingLinkIds.size===0&&delete i.floating,i.totalLinks===0&&this.removeReroute(i.id)}getLink(e){return e==null?void 0:this._links.get(e)}getReroute(e){return e==null?void 0:this.reroutes.get(e)}setReroute({id:e,parentId:t,pos:n,linkIds:i,floating:s}){e??=++this.state.lastRerouteId,e>this.state.lastRerouteId&&(this.state.lastRerouteId=e);const a=this.reroutes.get(e)??new J(e,this);return a.update(t,n,i,s),this.reroutes.set(e,a),a}createReroute(e,t){const n=Ae(),i=++this.state.lastRerouteId,s=t instanceof J?t.linkIds:[t.id],a=t instanceof J?t.floatingLinkIds:[t.id],r=new J(i,this,e,t.parentId,s,a);this.reroutes.set(i,r),n.setSource(ue.Canvas),n.createReroute(i,{x:e[0],y:e[1]},t.parentId,Array.from(s));for(const l of s){const d=this._links.get(l);if(!d)continue;d.parentId===t.parentId&&(d.parentId=i);const u=z.getReroutes(this,d);for(const p of u.filter(m=>m.parentId===t.parentId))p.parentId=i}for(const l of a){const d=this.floatingLinks.get(l);if(!d)continue;d.parentId===t.parentId&&(d.parentId=i);const u=z.getReroutes(this,d);for(const p of u.filter(m=>m.parentId===t.parentId))p.parentId=i}return r}removeReroute(e){const t=Ae(),{reroutes:n}=this,i=n.get(e);if(!i)return;this.canvasAction(l=>l.deselect(i));const{parentId:s,linkIds:a,floatingLinkIds:r}=i;for(const l of n.values())l.parentId===e&&(l.parentId=s);for(const l of a){const d=this._links.get(l);d&&d.parentId===e&&(d.parentId=s)}for(const l of r){const d=this.floatingLinks.get(l);if(!d){console.warn(`Removed reroute had floating link ID that did not exist [${l}]`);continue}const u=z.getReroutes(this,d),p=u.at(-1),m=u.at(-2);i===p&&(m?.totalLinks!==1?this.removeFloatingLink(d):d.parentId===e&&(d.parentId=s,m.floating=i.floating))}n.delete(e),t.setSource(ue.Canvas),t.deleteReroute(e),this.setDirtyCanvas(!1,!0)}removeLink(e){const t=this._links.get(e);t&&(this.getNodeById(t.target_id)?.disconnectInput(t.target_slot,!1),t.disconnect(this))}createSubgraph(e){const{id:t}=e,n=new De(this.rootGraph,e);return this.subgraphs.set(t,n),this.rootGraph.events.dispatch("subgraph-created",{subgraph:n,data:e}),n}convertToSubgraph(e){if(e.size===0)throw new Error("Cannot convert to subgraph: nothing to convert");this.beforeChange();try{return this._convertToSubgraphImpl(e)}finally{this.afterChange()}}_convertToSubgraphImpl(e){const{state:t,revision:n,config:i}=this,s=[...e][0];e.size===1&&s instanceof de&&(e=new Set([s]),s.recomputeInsideNodes(),s.children.forEach(x=>e.add(x)));const{boundaryLinks:a,boundaryFloatingLinks:r,internalLinks:l,boundaryInputLinks:d,boundaryOutputLinks:u}=Ns(this,e),{nodes:p,reroutes:m,groups:g}=Es(e),f=et(e);if(!f)throw new Error("Failed to create bounding rect for subgraph");const y=d.map(x=>x.resolve(this)),b=u.map(x=>x.resolve(this)),v=No(p),k=l.map(x=>x.asSerialisable()),w=new Map([...m].map(x=>[x.id,x])),S=new Map([...this.reroutes].filter(([x])=>!w.has(x))),E=xs(y,k,w),C=As(b,k,S),I={id:fe(),name:"New Subgraph",inputNode:{id:-10,bounding:[0,0,75,100]},outputNode:{id:-20,bounding:[0,0,75,100]},inputs:E,outputs:C,widgets:[],version:ge.serialisedSchemaVersion,state:t,revision:n,config:i,links:k,nodes:v,reroutes:structuredClone([...m].map(x=>x.asSerialisable())),groups:structuredClone([...g].map(x=>x.serialize()))},P=this.createSubgraph(I);P.configure(I);for(const x of P.nodes)x.onGraphConfigured?.();for(const x of P.nodes)x.onAfterGraphConfigured?.();P.inputNode.arrange(),P.outputNode.arrange();const{boundingRect:A}=P.inputNode,{boundingRect:F}=P.outputNode;po(A,ee.MidLeft,f,[50,0]),po(F,ee.MidRight,f,[50,0]);for(const x of y)x.inputNode?.disconnectInput(x.inputNode.inputs.indexOf(x.input),!0);for(const x of b)x.outputNode?.disconnectOutput(x.outputNode.outputs.indexOf(x.output),x.inputNode);for(const x of p)this.remove(x);for(const x of m)this.removeReroute(x.id);for(const x of g)this.remove(x);this.rootGraph.events.dispatch("convert-to-subgraph",{subgraph:P,bounds:f,exportedSubgraph:I,boundaryLinks:a,resolvedInputLinks:y,resolvedOutputLinks:b,boundaryFloatingLinks:r,internalLinks:l});const T=_.createNode(P.id,P.name,{outputs:structuredClone(C)});if(!T)throw new Error("Failed to create subgraph node");for(let x=0;x<E.length;x++)Object.assign(T.inputs[x],E[x]);T.setSize(T.computeSize()),Hi(T._posSize,ee.Centre|ee.Middle,f),T.pos[1]+=_.NODE_TITLE_HEIGHT/2,this.add(T);const $=St(y);let V=0;for(const[,x]of $.entries()){const[me,...Y]=x,{output:K,outputNode:Q,link:ne,subgraphInput:Ie}=me;if(V++,ne.origin_id===-10){if(ne.target_id=T.id,ne.target_slot=V-1,Ie instanceof kt)Ie.connect(T.findInputSlotByType(ne.type,!0,!0),T,ne.parentId);else throw new TypeError("Subgraph input node is not a SubgraphInput");for(const Kn of Y)Kn.link.disconnect(this);continue}if(!K||!Q){console.warn("Convert to Subgraph reconnect: Failed to resolve input link",x[0]);continue}const he=T.inputs[V-1];Q.connectSlots(K,T,he,ne.parentId)}const oe=St(b);V=0;for(const[,x]of oe.entries()){V++;for(const me of x){const{input:Y,inputNode:K,link:Q,subgraphOutput:ne}=me;if(Q.target_id===-20){if(Q.origin_id=T.id,Q.origin_slot=V-1,this.links.set(Q.id,Q),ne instanceof wt)ne.connect(T.findOutputSlotByType(Q.type,!0,!0),T,Q.parentId);else throw new TypeError("Subgraph input node is not a SubgraphInput");continue}if(!Y||!K){console.warn("Convert to Subgraph reconnect: Failed to resolve output link",me);continue}const Ie=T.outputs[V-1];T.connectSlots(Ie,K,Y,Q.parentId)}}return T._setConcreteSlots(),T.arrange(),this.canvasAction(x=>x.canvas.dispatchEvent(new CustomEvent("subgraph-converted",{bubbles:!0,detail:{subgraphNode:T}}))),{subgraph:P,node:T}}unpackSubgraph(e,t){if(!(e instanceof gt))throw new Error("Can only unpack Subgraph Nodes");this.beforeChange();try{this._unpackSubgraphImpl(e,t)}finally{this.afterChange()}}_unpackSubgraphImpl(e,t){const n=t?.skipMissingNodes??!1,i=et([...e.subgraph.nodes,...e.subgraph.reroutes.values(),...e.subgraph.groups].map(y=>({boundingRect:[y.pos[0],y.pos[1],y.size?.[0]??0,y.size?.[1]??0]})))??[0,0,0,0],s=[i[0]+i[2]/2,i[1]+i[3]/2],a=[],r=e.pos[0]-s[0]+e.size[0]/2,l=e.pos[1]-s[1]+e.size[1]/2,d=No(e.subgraph.nodes),u=new Map;for(const y of d){let b=_.createNode(String(y.type),y.title);if(!b)if(n)console.warn(`Cannot unpack node of type "${y.type}" - node type not found. Creating placeholder node.`),b=new q(y.title||y.type||"Missing Node"),b.last_serialization=y,b.has_errors=!0,b.type=String(y.type);else throw new Error(`Cannot unpack: node type "${y.type}" is not registered`);u.set(y.id,++this.last_node_id),b.id=this.last_node_id,y.id=this.last_node_id,this.add(b,!0),b.configure(y),b.pos[0]+=r,b.pos[1]+=l;for(const v of b.inputs)v.link=null;for(const v of b.outputs)v.links=[];a.push(b)}const p=structuredClone([...e.subgraph.groups].map(y=>y.serialize()));for(const y of p){const b=new de(y.title,y.id);this.add(b,!0),b.configure(y),b.pos[0]+=r,b.pos[1]+=l,a.push(b)}for(const y of e.inputs){if(!y.link)continue;const b=this.links.get(y.link);if(!b){console.warn("Broken link",y,y.link);continue}for(const v of z.getReroutes(this,b))v.linkIds.delete(b.id)}for(const y of e.outputs)for(const b of y.links??[]){const v=this.links.get(b);if(!v){console.warn("Broken link",y,b);continue}for(const k of z.getReroutes(this,v))k.linkIds.delete(v.id)}const m=[];for(const[,y]of e.subgraph._links){let b;if(y.origin_id===-10){const v=e.inputs[y.origin_slot].link;if(!v){console.error("Missing Link ID when unpacking");continue}const k=this.links[v];y.origin_id=k.origin_id,y.origin_slot=k.origin_slot,b=k.parentId}else{const v=u.get(y.origin_id);if(!v){console.error("Missing Link ID when unpacking");continue}y.origin_id=v}if(y.target_id===-20){for(const v of e.outputs[y.target_slot].links??[]){const k=this.links[v];m.push({oid:y.origin_id,oslot:y.origin_slot,tid:k.target_id,tslot:k.target_slot,id:y.id,iparent:y.parentId,eparent:k.parentId,externalFirst:!0}),k.parentId=void 0}continue}else{const v=u.get(y.target_id);if(!v){console.error("Missing Link ID when unpacking");continue}y.target_id=v}m.push({oid:y.origin_id,oslot:y.origin_slot,tid:y.target_id,tslot:y.target_slot,id:y.id,iparent:y.parentId,eparent:b,externalFirst:!1})}this.remove(e),this.subgraphs.delete(e.subgraph.id);const g=new Map;for(const y of m){let b;if(y.oid==-10){if(!(this instanceof De)){console.error("Ignoring link to subgraph outside subgraph");continue}const k=this._nodes_by_id[y.tid];b=this.inputNode.slots[y.oslot].connect(k.inputs[y.tslot],k)}else if(y.tid==-20){if(!(this instanceof De)){console.error("Ignoring link to subgraph outside subgraph");continue}const k=this._nodes_by_id[y.oid];b=this.outputNode.slots[y.tslot].connect(k.outputs[y.oslot],k)}else b=this._nodes_by_id[y.oid].connect(y.oslot,this._nodes_by_id[y.tid],y.tslot);if(!b){console.error("Failed to create link");continue}const v=g.get(y.id)??[];v.push(b.id),g.has(y.id)||g.set(y.id,v),y.id=b.id}const f=new Map;for(const y of e.subgraph.reroutes.values()){y.parentId!==void 0&&f.get(y.parentId)===void 0&&console.error("Missing Parent ID");const b=new J(++this.state.lastRerouteId,this,[y.pos[0]+r,y.pos[1]+l]);f.set(y.id,b.id),this.reroutes.set(b.id,b),a.push(b)}for(const y of m){const b=this.links.get(y.id);if(!b)continue;let v=b,k;if(y.externalFirst)for(k=y.eparent;k;){if(v.parentId=k,v=this.reroutes.get(k),!v){console.error("Broken Id link when unpacking");break}if(v.linkIds.has(b.id))throw new Error("Infinite parentId loop");v.linkIds.add(b.id),k=v.parentId}if(v){for(k=y.iparent;k;){const w=f.get(k);if(!w){console.error("Broken Id link when unpacking");break}if(v.parentId=w,v=this.reroutes.get(w),!v){console.error("Broken Id link when unpacking");break}if(v.linkIds.has(b.id))throw new Error("Infinite parentId loop");v.linkIds.add(b.id);const S=e.subgraph.reroutes.get(k);if(!S){console.error("Broken Id link when unpacking");break}k=S.parentId}if(!v)break;if(!y.externalFirst)for(k=y.eparent;k;){if(v.parentId=k,v=this.reroutes.get(k),!v){console.error("Broken Id link when unpacking");break}if(v.linkIds.has(b.id))throw new Error("Infinite parentId loop");v.linkIds.add(b.id),k=v.parentId}}}for(const y of u.values()){const b=this._nodes_by_id[y];b._setConcreteSlots(),b.arrange()}this.canvasAction(y=>y.selectItems(a))}resolveSubgraphIdPath(e){const t=[];let n=this.rootGraph;for(const i of e){const s=n.getNodeById(i);if(!s)throw new Error(`Node [${i}] not found. ID Path: ${e.join(":")}`);if(!s.isSubgraphNode())throw new Error(`Node [${i}] is not a SubgraphNode. ID Path: ${e.join(":")}`);t.push(s),n=s.subgraph}return t}serialize(e){const{config:t,state:n,groups:i,nodes:s,reroutes:a,extra:r,floatingLinks:l,definitions:d}=this.asSerialisable(e),u=[...this._links.values()],p=u.map(m=>m.serialize());return a?.length&&(r.linkExtensions=u.filter(m=>m.parentId!==void 0).map(m=>({id:m.id,parentId:m.parentId}))),r.reroutes=a?.length?a:void 0,{id:this.id,revision:this.revision,last_node_id:n.lastNodeId,last_link_id:n.lastLinkId,nodes:s,links:p,floatingLinks:l,groups:i,definitions:d,config:t,extra:r,version:_.VERSION}}#t(){const e=this.list_of_graphcanvas?.at(0)?.ds;if(e)return{scale:e.scale,offset:e.offset}}asSerialisable(e){const{id:t,revision:n,config:i,state:s}=this,a=(!_.use_uuids&&e?.sortNodes?[...this._nodes].sort((g,f)=>g.id-f.id):this._nodes).map(g=>g.serialize()),r=this._groups.map(g=>g.serialize()),l=this._links.size?[...this._links.values()].map(g=>g.asSerialisable()):void 0,d=this.floatingLinks.size?[...this.floatingLinks.values()].map(g=>g.asSerialisable()):void 0,u=this.reroutes.size?[...this.reroutes.values()].map(g=>g.asSerialisable()):void 0,p={...this.extra};_.saveViewportWithGraph&&(p.ds=this.#t()),p.ds||delete p.ds;const m={id:t,revision:n,version:ge.serialisedSchemaVersion,config:i,state:s,groups:r,nodes:a,links:l,floatingLinks:d,reroutes:u,extra:p};if(this.isRootGraph&&this._subgraphs.size){const g=Os(this,this._subgraphs),f=[...this._subgraphs.values()].filter(y=>g.has(y.id)).map(y=>y.asSerialisable());f.length>0&&(m.definitions={subgraphs:f})}return this.onSerialize?.(m),m}_configureBase(e){const{id:t,extra:n}=e;t?this.id=t:this.id==="00000000-0000-0000-0000-000000000000"&&(this.id=fe()),this.extra=n?structuredClone(n):{},delete this.extra.linkExtensions}configure(e,t){const n=Ae(),i={data:e,clearGraph:!t};if(this.events.dispatch("configuring",i))try{if(!e)return;i.clearGraph&&this.clear(),this._configureBase(e);let s;if(e.version===.4){const{extra:g}=e;if(Array.isArray(e.links))for(const f of e.links){const y=z.createFromArray(f);this._links.set(y.id,y)}if(Array.isArray(g?.linkExtensions))for(const f of g.linkExtensions){const y=this._links.get(f.id);y&&(y.parentId=f.parentId)}s=g?.reroutes}else{if(e.state){const{lastGroupId:g,lastLinkId:f,lastNodeId:y,lastRerouteId:b}=e.state,{state:v}=this;g!=null&&(v.lastGroupId=g),f!=null&&(v.lastLinkId=f),y!=null&&(v.lastNodeId=y),b!=null&&(v.lastRerouteId=b)}if(Array.isArray(e.links))for(const g of e.links){const f=z.create(g);this._links.set(f.id,f)}s=e.reroutes}if(Array.isArray(s))for(const g of s)this.setReroute(g);const a=e.nodes;for(const g in e)ge.ConfigureProperties.has(g)||(this[g]=e[g]);const r=e.definitions?.subgraphs;if(r){for(const g of r)this.createSubgraph(g);for(const g of r)this.subgraphs.get(g.id)?.configure(g)}let l=!1;const d=new Map;if(this._nodes=[],a){for(const g of a){let f=_.createNode(String(g.type),g.title);f||(_.debug&&console.warn("Node not found or has errors:",g.type),f=new q(""),f.last_serialization=g,f.has_errors=!0,l=!0),f.id=g.id,this.add(f,!0),d.set(f.id,g)}for(const[g,f]of d)this.getNodeById(g)?.configure(f)}if(Array.isArray(e.floatingLinks))for(const g of e.floatingLinks){const f=z.create(g);this.addFloatingLink(f),f.id>this.#e&&(this.#e=f.id)}for(const g of this.reroutes.values())g.validateLinks(this._links,this.floatingLinks)||(this.reroutes.delete(g.id),n.setSource(ue.Canvas),n.deleteReroute(g.id));this._groups.length=0;const u=e.groups;if(u)for(const g of u){const f=new _.LGraphGroup;f.configure(g),this.add(f)}this.updateExecutionOrder(),this.onConfigure?.(e),this._version++;const{primaryCanvas:p}=this,m=p?.subgraph?.id;if(m){const g=this.subgraphs.get(m);g?p.setGraph(g):p.setGraph(this)}return this.setDirtyCanvas(!0,!0),l}finally{this.events.dispatch("configured")}}#o;get primaryCanvas(){return this.rootGraph.#o}set primaryCanvas(e){this.rootGraph.#o=e}load(e,t){if(e instanceof Blob||e instanceof File){const i=new FileReader;i.addEventListener("load",s=>{const a=$t(s.target?.result),r=JSON.parse(a);this.configure(r),t?.()}),i.readAsText(e);return}const n=new XMLHttpRequest;n.open("GET",e,!0),n.send(null),n.addEventListener("load",()=>{if(n.status!==200){console.error("Error loading graph:",n.status,n.response);return}const i=JSON.parse(n.response);this.configure(i),t?.()}),n.addEventListener("error",i=>{console.error("Error loading graph:",i)})}},De=class On extends Zt{static{h(this,"Subgraph")}events=new Et;static MAX_NESTED_SUBGRAPHS=1e3;name="Unnamed Subgraph";inputNode=new Nt(this);outputNode=new xt(this);inputs=[];outputs=[];widgets=[];#e;get rootGraph(){return this.#e}constructor(e,t){if(!e)throw new Error("Root graph is required");super(),this.#e=e;const n=structuredClone(t);this._configureBase(n),this.#t(n)}getIoNodeOnPos(e,t){const{inputNode:n,outputNode:i}=this;if(n.containsPoint([e,t]))return n;if(i.containsPoint([e,t]))return i}#t(e){const{name:t,inputs:n,outputs:i,widgets:s}=e;if(this.name=t,n){this.inputs.length=0;for(const a of n){const r=new kt(a,this.inputNode);this.inputs.push(r),this.events.dispatch("input-added",{input:r})}}if(i){this.outputs.length=0;for(const a of i)this.outputs.push(new wt(a,this.outputNode))}if(s){this.widgets.length=0;for(const a of s)this.widgets.push(a)}this.inputNode.configure(e.inputNode),this.outputNode.configure(e.outputNode)}configure(e,t){const n=super.configure(e,t);return this.#t(e),n}attachCanvas(e){super.attachCanvas(e),e.subgraph=this}addInput(e,t){this.events.dispatch("adding-input",{name:e,type:t});const n=new kt({id:fe(),name:e,type:t},this.inputNode);return this.inputs.push(n),this.events.dispatch("input-added",{input:n}),n}addOutput(e,t){this.events.dispatch("adding-output",{name:e,type:t});const n=new wt({id:fe(),name:e,type:t},this.outputNode);return this.outputs.push(n),this.events.dispatch("output-added",{output:n}),n}renameInput(e,t){const n=this.inputs.indexOf(e);if(n===-1)throw new Error("Input not found");const i=e.displayName;this.events.dispatch("renaming-input",{input:e,index:n,oldName:i,newName:t}),e.label=t}renameOutput(e,t){const n=this.outputs.indexOf(e);if(n===-1)throw new Error("Output not found");const i=e.displayName;this.events.dispatch("renaming-output",{output:e,index:n,oldName:i,newName:t}),e.label=t}removeInput(e){e.disconnect();const t=this.inputs.indexOf(e);if(t===-1)throw new Error("Input not found");if(!this.events.dispatch("removing-input",{input:e,index:t}))return;this.inputs.splice(t,1);const{length:n}=this.inputs;for(let i=t;i<n;i++)this.inputs[i].decrementSlots("inputs")}removeOutput(e){e.disconnect();const t=this.outputs.indexOf(e);if(t===-1)throw new Error("Output not found");if(!this.events.dispatch("removing-output",{output:e,index:t}))return;this.outputs.splice(t,1);const{length:n}=this.outputs;for(let i=t;i<n;i++)this.outputs[i].decrementSlots("outputs")}draw(e,t,n,i){this.inputNode.draw(e,t,n,i),this.outputNode.draw(e,t,n,i)}clone(e=!1){const t=this.asSerialisable();e||(t.id=fe());const n=new On(this.rootGraph,t);return n.configure(t),n}asSerialisable(){return{id:this.id,version:Zt.serialisedSchemaVersion,state:this.state,revision:this.revision,config:this.config,name:this.name,inputNode:this.inputNode.asSerialisable(),outputNode:this.outputNode.asSerialisable(),inputs:this.inputs.map(e=>e.asSerialisable()),outputs:this.outputs.map(e=>e.asSerialisable()),widgets:[...this.widgets],nodes:this.nodes.map(e=>e.serialize()),groups:this.groups.map(e=>e.serialize()),links:[...this.links.values()].map(e=>e.asSerialisable()),reroutes:this.reroutes.size?[...this.reroutes.values()].map(e=>e.asSerialisable()):void 0,extra:this.extra}}},Uw=class{static{h(this,"InputIndicators")}radius=8;startAngle=0;endAngle=Math.PI*2;inactiveColour="#ffffff10";colour1="#ff5f00";colour2="#00ff7c";colour3="#dea7ff";fontString="bold 12px Inter, sans-serif";enabled=!0;shiftDown=!1;undoDown=!1;redoDown=!1;ctrlDown=!1;altDown=!1;mouse0Down=!1;mouse1Down=!1;mouse2Down=!1;x=0;y=0;controller;constructor(o){this.canvas=o,this.controller=new AbortController;const{signal:e}=this.controller,t=o.canvas,n={capture:!0,signal:e};t.addEventListener("pointerdown",this.#e,n),t.addEventListener("pointermove",this.#e,n),t.addEventListener("pointerup",this.#t,n),t.addEventListener("keydown",this.#o,n),document.addEventListener("keyup",this.#o,n);const i=o.drawFrontCanvas.bind(o);e.addEventListener("abort",()=>{o.drawFrontCanvas=i}),o.drawFrontCanvas=()=>{i(),this.draw()}}#e=this.onPointerDownOrMove.bind(this);onPointerDownOrMove(o){this.mouse0Down=(o.buttons&1)===1,this.mouse1Down=(o.buttons&4)===4,this.mouse2Down=(o.buttons&2)===2,this.x=o.clientX,this.y=o.clientY,this.canvas.setDirty(!0)}#t=this.onPointerUp.bind(this);onPointerUp(){this.mouse0Down=!1,this.mouse1Down=!1,this.mouse2Down=!1}#o=this.onKeyDownOrUp.bind(this);onKeyDownOrUp(o){this.ctrlDown=o.ctrlKey,this.altDown=o.altKey,this.shiftDown=o.shiftKey,this.undoDown=o.ctrlKey&&o.code==="KeyZ"&&o.type==="keydown",this.redoDown=o.ctrlKey&&o.code==="KeyY"&&o.type==="keydown"}draw(){const{canvas:{ctx:o},radius:e,startAngle:t,endAngle:n,x:i,y:s,inactiveColour:a,colour1:r,colour2:l,colour3:d,fontString:u}=this,{fillStyle:p,font:m}=o,g=i,f=s-80,y=g,b=f-15;o.font=u,S(y+0,b,"Shift",this.shiftDown?r:a),S(y+45,b+20,"Alt",this.altDown?l:a),S(y+30,b,"Control",this.ctrlDown?d:a),S(y-30,b,"↩️",this.undoDown?"#000":"transparent"),S(y+45,b,"↪️",this.redoDown?"#000":"transparent"),o.beginPath(),C(g,f),C(g+15,f),C(g+30,f),o.fillStyle=a,o.fill();const v=this.mouse0Down?r:a,k=this.mouse1Down?l:a,w=this.mouse2Down?d:a;this.mouse0Down&&E(g,f,v),this.mouse1Down&&E(g+15,f,k),this.mouse2Down&&E(g+30,f,w),o.fillStyle=p,o.font=m;function S(I,P,A,F){o.fillStyle=F,o.fillText(A,I,P)}h(S,"textMarker");function E(I,P,A){o.beginPath(),o.fillStyle=A,C(I,P),o.fill()}h(E,"mouseMarker");function C(I,P){o.arc(I,P,e,t,n)}h(C,"drawDot")}dispose(){this.controller?.abort(),this.controller=void 0}[Symbol.dispose](){this.dispose()}},Ww=class{static{h(this,"LiteGraphGlobal")}SlotShape=Ne;SlotDirection=ws;SlotType=pt;LabelPosition=tt;VERSION=.4;CANVAS_GRID_SIZE=10;NODE_TITLE_HEIGHT=30;NODE_TITLE_TEXT_Y=20;NODE_SLOT_HEIGHT=20;NODE_WIDGET_HEIGHT=20;NODE_WIDTH=140;NODE_MIN_WIDTH=50;NODE_COLLAPSED_RADIUS=10;NODE_COLLAPSED_WIDTH=80;NODE_TITLE_COLOR="#999";NODE_SELECTED_TITLE_COLOR="#FFF";NODE_TEXT_SIZE=14;NODE_TEXT_COLOR="#AAA";NODE_TEXT_HIGHLIGHT_COLOR="#EEE";NODE_SUBTEXT_SIZE=12;NODE_DEFAULT_COLOR="#333";NODE_DEFAULT_BGCOLOR="#353535";NODE_DEFAULT_BOXCOLOR="#666";NODE_DEFAULT_SHAPE=M.ROUND;NODE_BOX_OUTLINE_COLOR="#FFF";NODE_ERROR_COLOUR="#E00";NODE_FONT="Inter";NODE_DEFAULT_BYPASS_COLOR="#FF00FF";NODE_OPACITY=.9;DEFAULT_FONT="Inter";DEFAULT_SHADOW_COLOR="rgba(0,0,0,0.5)";DEFAULT_GROUP_FONT=24;DEFAULT_GROUP_FONT_SIZE=24;GROUP_FONT="Inter";WIDGET_BGCOLOR="#222";WIDGET_OUTLINE_COLOR="#666";WIDGET_PROMOTED_OUTLINE_COLOR="#BF00FF";WIDGET_ADVANCED_OUTLINE_COLOR="rgba(56, 139, 253, 0.8)";WIDGET_TEXT_COLOR="#DDD";WIDGET_SECONDARY_TEXT_COLOR="#999";WIDGET_DISABLED_TEXT_COLOR="#666";LINK_COLOR="#9A9";EVENT_LINK_COLOR="#A86";CONNECTING_LINK_COLOR="#AFA";MAX_NUMBER_OF_NODES=1e4;DEFAULT_POSITION=[100,100];VALID_SHAPES=["default","box","round","card"];ROUND_RADIUS=8;BOX_SHAPE=M.BOX;ROUND_SHAPE=M.ROUND;CIRCLE_SHAPE=M.CIRCLE;CARD_SHAPE=M.CARD;ARROW_SHAPE=M.ARROW;GRID_SHAPE=M.GRID;INPUT=j.INPUT;OUTPUT=j.OUTPUT;EVENT=-1;ACTION=-1;NODE_MODES=["Always","On Event","Never","On Trigger"];NODE_MODES_COLORS=["#666","#422","#333","#224","#626"];ALWAYS=H.ALWAYS;ON_EVENT=H.ON_EVENT;NEVER=H.NEVER;ON_TRIGGER=H.ON_TRIGGER;UP=O.UP;DOWN=O.DOWN;LEFT=O.LEFT;RIGHT=O.RIGHT;CENTER=O.CENTER;LINK_RENDER_MODES=["Straight","Linear","Spline"];HIDDEN_LINK=ie.HIDDEN_LINK;STRAIGHT_LINK=ie.STRAIGHT_LINK;LINEAR_LINK=ie.LINEAR_LINK;SPLINE_LINK=ie.SPLINE_LINK;NORMAL_TITLE=se.NORMAL_TITLE;NO_TITLE=se.NO_TITLE;TRANSPARENT_TITLE=se.TRANSPARENT_TITLE;AUTOHIDE_TITLE=se.AUTOHIDE_TITLE;VERTICAL_LAYOUT="vertical";proxy=null;node_images_path="";debug=!1;catch_exceptions=!0;throw_errors=!0;allow_scripts=!1;registered_node_types={};node_types_by_file_extension={};Nodes={};Globals={};searchbox_extras={};node_box_coloured_when_on=!1;node_box_coloured_by_mode=!1;dialog_close_on_mouse_leave=!1;dialog_close_on_mouse_leave_delay=500;shift_click_do_break_link_from=!1;click_do_break_link_to=!1;ctrl_alt_click_do_break_link=!0;snaps_for_comfy=!0;snap_highlights_node=!0;alwaysSnapToGrid;snapToGrid;search_hide_on_mouse_leave=!0;search_filter_enabled=!1;search_show_all_on_open=!0;auto_load_slot_types=!1;registered_slot_in_types={};registered_slot_out_types={};slot_types_in=[];slot_types_out=[];slot_types_default_in={};slot_types_default_out={};alt_drag_do_clone_nodes=!1;do_add_triggers_slots=!1;allow_multi_output_for_events=!0;middle_click_slot_add_default_node=!1;release_link_on_empty_shows_menu=!1;pointerevents_method="pointer";ctrl_shift_v_paste_connect_unselected_outputs=!0;use_uuids=!1;highlight_selected_group=!0;context_menu_scaling=!1;alwaysRepeatWarnings=!1;onDeprecationWarning=[console.warn];macTrackpadGestures=!1;macGesturesRequireMac=!0;canvasNavigationMode="legacy";leftMouseClickBehavior="panning";mouseWheelScroll="panning";truncateWidgetTextEvenly=!1;truncateWidgetValuesFirst=!1;saveViewportWithGraph=!0;vueNodesMode=!1;nodeOpacity=1;nodeLightness=void 0;LGraph=Zt;LLink=z;LGraphNode=q;LGraphGroup=de;DragAndScale=tn;LGraphCanvas=ce;ContextMenu=zi;CurveEditor=ji;Reroute=J;constructor(){Object.defineProperty(this,"Classes",{writable:!1})}Classes={get SubgraphSlot(){return so},get SubgraphIONodeBase(){return _e},get Rectangle(){return X},get InputIndicators(){return Uw}};registerNodeType(o,e){if(!e.prototype)throw"Cannot register a simple object, it must be a class with a prototype";e.type=o;const t=e.name,n=o.lastIndexOf("/");e.category=o.substring(0,n),e.title||=t;for(const s in q.prototype)e.prototype[s]||=q.prototype[s];const i=this.registered_node_types[o];i&&this.debug&&console.warn("replacing node type:",o),this.registered_node_types[o]=e,e.constructor.name&&(this.Nodes[t]=e),this.onNodeTypeRegistered?.(o,e),i&&this.onNodeTypeReplaced?.(o,e,i),e.prototype.onPropertyChange&&console.warn(`LiteGraph node class ${o} has onPropertyChange method, it must be called onPropertyChanged with d at the end`),this.auto_load_slot_types&&new e(e.title||"tmpnode")}unregisterNodeType(o){const e=typeof o=="string"?this.registered_node_types[o]:o;if(!e)throw`node type not found: ${String(o)}`;delete this.registered_node_types[String(e.type)];const t=e.constructor.name;t&&delete this.Nodes[t]}registerNodeAndSlotType(o,e,t){t||=!1;const n=(typeof o=="string"&&this.registered_node_types[o]!=="anonymous"?this.registered_node_types[o]:o).constructor.type;let i=[];typeof e=="string"?i=e.split(","):e==this.EVENT||e==this.ACTION?i=["_event_"]:i=["*"];for(let s of i){s===""&&(s="*");const a=t?this.registered_slot_out_types:this.registered_slot_in_types;a[s]??={nodes:[]};const{nodes:r}=a[s];r.includes(n)||r.push(n);const l=t?this.slot_types_out:this.slot_types_in,d=s.toLowerCase();l.includes(d)||(l.push(d),l.sort())}}clearRegisteredTypes(){this.registered_node_types={},this.node_types_by_file_extension={},this.Nodes={},this.searchbox_extras={}}createNode(o,e,t){const n=this.registered_node_types[o];if(!n)return this.debug&&console.warn(`GraphNode type "${o}" not registered.`),null;e=e||n.title||o;let i=null;if(this.catch_exceptions)try{i=new n(e)}catch(s){return console.error(s),null}else i=new n(e);if(i.type=o,!i.title&&e&&(i.title=e),i.properties||={},i.properties_info||=[],i.flags||={},i.size||=i.computeSize(),i.pos||=[this.DEFAULT_POSITION[0],this.DEFAULT_POSITION[1]],i.mode||=H.ALWAYS,t)for(const s in t)i[s]=t[s];return i.onNodeCreated?.(),i}getNodeType(o){return this.registered_node_types[o]}getNodeTypesInCategory(o,e){const t=[];for(const n in this.registered_node_types){const i=this.registered_node_types[n];i.filter==e&&(o==""?i.category==null&&t.push(i):i.category==o&&t.push(i))}return t}getNodeTypesCategories(o){const e={"":1};for(const n in this.registered_node_types){const i=this.registered_node_types[n];if(i.category&&!i.skip_list){if(i.filter!=o)continue;e[i.category]=1}}const t=[];for(const n in e)t.push(n);return t}reloadNodes(o){const e=document.getElementsByTagName("script"),t=[];for(const i of e)t.push(i);const n=document.getElementsByTagName("head")[0];o=document.location.href+o;for(const i of t){const s=i.src;if(!(!s||s.substr(0,o.length)!=o))try{const a=document.createElement("script");a.type="text/javascript",a.src=s,n.append(a),i.remove()}catch(a){if(this.throw_errors)throw a;this.debug&&console.error("Error while reloading",s)}}}cloneObject(o,e){if(o==null)return null;const t=JSON.parse(JSON.stringify(o));if(!e)return t;for(const n in t)e[n]=t[n];return e}uuidv4=fe;isValidConnection(o,e){if((o==""||o==="*")&&(o=0),(e==""||e==="*")&&(e=0),!o||!e||o==e||o==this.EVENT&&e==this.ACTION)return!0;if(o=String(o),e=String(e),o=o.toLowerCase(),e=e.toLowerCase(),!o.includes(",")&&!e.includes(","))return o==e;const t=o.split(","),n=e.split(",");for(const i of t)for(const s of n)if(this.isValidConnection(i,s))return!0;return!1}getParameterNames(o){return String(o).replaceAll(/\/\/.*$/gm,"").replaceAll(/\s+/g,"").replaceAll(/\/\*[^*/]*\*\//g,"").split("){",1)[0].replace(/^[^(]*\(/,"").replaceAll(/=[^,]+/g,"").split(",").filter(Boolean)}pointerListenerAdd(o,e,t,n=!1){if(!o||!o.addEventListener||!e||typeof t!="function")return;let i=this.pointerevents_method,s=e;if(i=="pointer"&&!window.PointerEvent)switch(console.warn("sMethod=='pointer' && !window.PointerEvent"),console.warn(`Converting pointer[${s}] : down move up cancel enter TO touchstart touchmove touchend, etc ..`),s){case"down":i="touch",s="start";break;case"move":i="touch";break;case"up":i="touch",s="end";break;case"cancel":i="touch";break;case"enter":break;default:console.warn(`PointerEvent not available in this browser ? The event ${s} would not be called`)}switch(s){case"down":case"up":case"move":case"over":case"out":case"enter":o.addEventListener(i+s,t,n);case"leave":case"cancel":case"gotpointercapture":case"lostpointercapture":if(i!="mouse")return o.addEventListener(i+s,t,n);default:return o.addEventListener(s,t,n)}}pointerListenerRemove(o,e,t,n=!1){if(!(!o||!o.removeEventListener||!e||typeof t!="function"))switch(e){case"down":case"up":case"move":case"over":case"out":case"enter":(this.pointerevents_method=="pointer"||this.pointerevents_method=="mouse")&&o.removeEventListener(this.pointerevents_method+e,t,n);case"leave":case"cancel":case"gotpointercapture":case"lostpointercapture":if(this.pointerevents_method=="pointer")return o.removeEventListener(this.pointerevents_method+e,t,n);default:return o.removeEventListener(e,t,n)}}getTime(){return performance.now()}distance=Ue;colorToString(o){return`rgba(${Math.round(o[0]*255).toFixed()},${Math.round(o[1]*255).toFixed()},${Math.round(o[2]*255).toFixed()},${o.length==4?o[3].toFixed(2):"1.0"})`}isInsideRectangle=Ui;growBounding(o,e,t){e<o[0]?o[0]=e:e>o[2]&&(o[2]=e),t<o[1]?o[1]=t:t>o[3]&&(o[3]=t)}overlapBounding=Le;isInsideBounding(o,e){return!(o[0]<e[0][0]||o[1]<e[0][1]||o[0]>e[1][0]||o[1]>e[1][1])}hex2num(o){o.charAt(0)=="#"&&(o=o.slice(1)),o=o.toUpperCase();const e="0123456789ABCDEF",t=new Array(3);let n=0,i,s;for(let a=0;a<6;a+=2)i=e.indexOf(o.charAt(a)),s=e.indexOf(o.charAt(a+1)),t[n]=i*16+s,n++;return t}num2hex(o){const e="0123456789ABCDEF";let t="#",n,i;for(let s=0;s<3;s++)n=o[s]/16,i=o[s]%16,t+=e.charAt(n)+e.charAt(i);return t}closeAllContextMenus(o=window){const e=[...o.document.querySelectorAll(".litecontextmenu")];if(e.length)for(const t of e)"close"in t&&typeof t.close=="function"?t.close():t.remove()}extendClass(o,e){for(const t in e)o.hasOwnProperty(t)||(o[t]=e[t]);if(e.prototype&&o.prototype){const t=e.prototype,n=o.prototype;for(const i in t){if(!t.hasOwnProperty(i)||n.hasOwnProperty(i))continue;const s=Object.getOwnPropertyDescriptor(t,i);s&&Object.defineProperty(n,i,s)}}}};Symbol.dispose??=Symbol("Symbol.dispose");Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");function Gw(){typeof window<"u"&&window.CanvasRenderingContext2D&&!window.CanvasRenderingContext2D.prototype.roundRect&&(window.CanvasRenderingContext2D.prototype.roundRect=function(o,e,t,n,i,s){let a=0,r=0,l=0,d=0;if(i===0){this.rect(o,e,t,n);return}if(s===void 0&&(s=i),Array.isArray(i))if(i.length==1)a=r=l=d=i[0];else if(i.length==2)a=d=i[0],r=l=i[1];else if(i.length==4)a=i[0],r=i[1],l=i[2],d=i[3];else return;else{a=i||0,r=i||0;const u=!Array.isArray(s)&&s?s:0;l=u,d=u}this.moveTo(o+a,e),this.lineTo(o+t-r,e),this.quadraticCurveTo(o+t,e,o+t,e+r),this.lineTo(o+t,e+n-d),this.quadraticCurveTo(o+t,e+n,o+t-d,e+n),this.lineTo(o+d,e+n),this.quadraticCurveTo(o,e+n,o,e+n-l),this.lineTo(o,e+l),this.quadraticCurveTo(o,e,o+a,e)}),typeof window<"u"&&!window.requestAnimationFrame&&(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(o){window.setTimeout(o,1e3/60)})}h(Gw,"loadPolyfills");const _=new Ww;Gw();var Pn=c.object({CLIP:c.string(),CLIP_VISION:c.string(),CLIP_VISION_OUTPUT:c.string(),CONDITIONING:c.string(),CONTROL_NET:c.string(),IMAGE:c.string(),LATENT:c.string(),MASK:c.string(),MODEL:c.string(),STYLE_MODEL:c.string(),VAE:c.string(),NOISE:c.string(),GUIDER:c.string(),SAMPLER:c.string(),SIGMAS:c.string(),TAESD:c.string()}),Mn=c.object({BACKGROUND_IMAGE:c.string(),CLEAR_BACKGROUND_COLOR:c.string(),NODE_TITLE_COLOR:c.string(),NODE_SELECTED_TITLE_COLOR:c.string(),NODE_TEXT_SIZE:c.number(),NODE_TEXT_COLOR:c.string(),NODE_TEXT_HIGHLIGHT_COLOR:c.string(),NODE_SUBTEXT_SIZE:c.number(),NODE_DEFAULT_COLOR:c.string(),NODE_DEFAULT_BGCOLOR:c.string(),NODE_DEFAULT_BOXCOLOR:c.string(),NODE_DEFAULT_SHAPE:c.union([c.literal(_.BOX_SHAPE),c.literal(_.ROUND_SHAPE),c.literal(_.CARD_SHAPE),c.string()]),NODE_BOX_OUTLINE_COLOR:c.string(),NODE_BYPASS_BGCOLOR:c.string(),NODE_ERROR_COLOUR:c.string(),DEFAULT_SHADOW_COLOR:c.string(),DEFAULT_GROUP_FONT:c.number(),WIDGET_BGCOLOR:c.string(),WIDGET_OUTLINE_COLOR:c.string(),WIDGET_TEXT_COLOR:c.string(),WIDGET_SECONDARY_TEXT_COLOR:c.string(),WIDGET_DISABLED_TEXT_COLOR:c.string(),LINK_COLOR:c.string(),EVENT_LINK_COLOR:c.string(),CONNECTING_LINK_COLOR:c.string(),BADGE_FG_COLOR:c.string(),BADGE_BG_COLOR:c.string()});const Rn=c.object({"fg-color":c.string(),"bg-color":c.string(),"bg-img":c.string().optional(),"comfy-menu-bg":c.string(),"comfy-menu-secondary-bg":c.string(),"comfy-input-bg":c.string(),"input-text":c.string(),"descrip-text":c.string(),"drag-text":c.string(),"error-text":c.string(),"border-color":c.string(),"tr-even-bg-color":c.string(),"tr-odd-bg-color":c.string(),"content-bg":c.string(),"content-fg":c.string(),"content-hover-bg":c.string(),"content-hover-fg":c.string(),"bar-shadow":c.string(),"contrast-mix-color":c.string().optional(),"interface-stroke":c.string().optional(),"interface-panel-surface":c.string().optional(),"interface-panel-box-shadow":c.string().optional(),"interface-panel-drop-shadow":c.string().optional(),"interface-panel-hover-surface":c.string().optional(),"interface-panel-selected-surface":c.string().optional(),"interface-button-hover-surface":c.string().optional()});var Hw=c.object({node_slot:Pn,litegraph_base:Mn,comfy_base:Rn}),jw=c.object({node_slot:Pn.partial(),litegraph_base:Mn.partial(),comfy_base:Rn.partial()});const qw=c.object({id:c.string(),name:c.string(),colors:jw,light_theme:c.boolean().optional()}).passthrough();c.object({id:c.string(),name:c.string(),colors:Hw}).passthrough();const $w=c.record(qw);var Kw=c.object({key:c.string(),ctrl:c.boolean().optional(),alt:c.boolean().optional(),shift:c.boolean().optional(),meta:c.boolean().optional()});const Ro=c.object({commandId:c.string(),combo:Kw,targetElementId:c.string().optional()});let ft=(function(o){return o.Core="core",o.CustomNodes="custom_nodes",o.Blueprint="blueprint",o.Unknown="unknown",o})({});var Fo={type:ft.Unknown,className:"comfy-unknown",displayText:"Unknown",badgeText:"?"},Xw=h(o=>o.replace(/^(ComfyUI-|ComfyUI_|Comfy-|Comfy_)/,"").replace(/(-ComfyUI|_ComfyUI|-Comfy|_Comfy)$/,""),"shortenNodeName");const oI=h(o=>{if(!o)return Fo;const e=o.split(".");if(["nodes","comfy_extras","comfy_api_nodes"].includes(e[0]))return{type:ft.Core,className:"comfy-core",displayText:"Comfy Core",badgeText:"🦊"};if(e[0]==="blueprint")return{type:ft.Blueprint,className:"blueprint",displayText:"Blueprint",badgeText:"bp"};if(e[0]==="custom_nodes"){const t=e[1].split("@")[0],n=Xw(t);return{type:ft.CustomNodes,className:"comfy-custom-nodes",displayText:n,badgeText:n}}else return Fo},"getNodeSource");let Yw=(function(o){return o.None="None",o.ShowAll="Show all",o.HideBuiltIn="Hide built-in",o})({}),Qw=(function(o){return o.CONTEXT_MENU="context menu",o.SEARCH_BOX="search box",o.NO_ACTION="no action",o})({});var Fn=c.string(),ot=c.string();const zn=c.enum(["input","output","temp"]);var Ht=c.object({filename:c.string().optional(),subfolder:c.string().optional(),type:zn.optional()}),Bn=c.object({audio:c.array(Ht).optional(),images:c.array(Ht).optional(),video:c.array(Ht).optional(),animated:c.array(c.boolean()).optional(),text:c.union([c.string(),c.array(c.string())]).optional()}).passthrough(),Zw=c.object({exec_info:c.object({queue_remaining:c.number().int()})});c.object({status:Zw.nullish(),sid:c.string().nullish()});c.object({value:c.number().int(),max:c.number().int(),prompt_id:ot,node:W});var Jw=c.object({value:c.number(),max:c.number(),state:c.enum(["pending","running","finished","error"]),node_id:W,prompt_id:ot,display_node_id:W.optional(),parent_node_id:W.optional(),real_node_id:W.optional()});c.object({prompt_id:ot,nodes:c.record(W,Jw)});c.object({node:W,display_node:W,prompt_id:ot}).extend({output:Bn,merge:c.boolean().optional()});var ao=c.object({prompt_id:ot,timestamp:c.number().int()});ao.extend({nodes:c.array(W)});ao.extend({node_id:W,node_type:Fn,executed:c.array(W)});ao.extend({node_id:W,node_type:Fn,executed:c.array(W),exception_message:c.string(),exception_type:c.string(),traceback:c.array(c.string()),current_inputs:c.any(),current_outputs:c.any()});c.object({nodeId:W,text:c.string()});c.object({value:c.string(),id:c.string().optional()});var Vn=c.object({cols:c.number(),row:c.number()}),Un=c.object({t:c.string(),m:c.string()});c.object({size:Vn.optional(),entries:c.array(Un)});c.object({size:Vn,entries:c.array(Un)});c.record(c.string(),c.any());c.object({task_id:c.string(),asset_name:c.string(),bytes_total:c.number(),bytes_downloaded:c.number(),progress:c.number(),status:c.enum(["created","running","completed","failed"]),asset_id:c.string().optional(),error:c.string().optional()});const eS=c.record(W,Bn);c.array(c.string());c.array(c.string());var Wn=c.object({type:c.string(),message:c.string(),details:c.string(),extra_info:c.object({input_name:c.string().optional()}).passthrough().optional()}),tS=c.object({errors:c.array(Wn),class_type:c.string(),dependent_outputs:c.array(c.any())});c.object({node_errors:c.record(W,tS).optional(),prompt_id:c.string().optional(),exec_info:c.object({queue_remaining:c.number().optional()}).optional(),error:c.union([c.string(),Wn])});var oS=c.object({name:c.string(),type:c.string(),index:c.number(),vram_total:c.number(),vram_free:c.number(),torch_vram_total:c.number(),torch_vram_free:c.number()});c.object({system:c.object({os:c.string(),python_version:c.string(),embedded_python:c.boolean(),comfyui_version:c.string(),pytorch_version:c.string(),required_frontend_version:c.string().optional(),argv:c.array(c.string()),ram_total:c.number(),ram_free:c.number(),cloud_version:c.string().optional(),comfyui_frontend_version:c.string().optional(),workflow_templates_version:c.string().optional()}),devices:c.array(oS)});c.object({storage:c.enum(["server"]),migrated:c.boolean().optional(),users:c.record(c.string(),c.string()).optional()});c.array(c.array(c.string(),c.string()));c.object({path:c.string(),size:c.number(),modified:c.number()});var nS=c.object({icon:c.string().optional(),color:c.string().optional()}),zo=c.enum(Object.values(Qw)),jt=c.enum(Object.values(Yw)),iS=c.enum(["default","none","auto","latent2rgb","taesd"]);c.object({"Comfy.ColorPalette":c.string(),"Comfy.CustomColorPalettes":$w,"Comfy.Canvas.BackgroundImage":c.string().optional(),"Comfy.ConfirmClear":c.boolean(),"Comfy.DevMode":c.boolean(),"Comfy.UI.TabBarLayout":c.enum(["Default","Integrated"]),"Comfy.Workflow.ShowMissingNodesWarning":c.boolean(),"Comfy.Workflow.ShowMissingModelsWarning":c.boolean(),"Comfy.Workflow.WarnBlueprintOverwrite":c.boolean(),"Comfy.DisableFloatRounding":c.boolean(),"Comfy.DisableSliders":c.boolean(),"Comfy.DOMClippingEnabled":c.boolean(),"Comfy.EditAttention.Delta":c.number(),"Comfy.EnableTooltips":c.boolean(),"Comfy.EnableWorkflowViewRestore":c.boolean(),"Comfy.FloatRoundingPrecision":c.number(),"Comfy.Graph.CanvasInfo":c.boolean(),"Comfy.Graph.CanvasMenu":c.boolean(),"Comfy.Graph.CtrlShiftZoom":c.boolean(),"Comfy.Graph.LiveSelection":c.boolean(),"Comfy.Graph.LinkMarkers":c.nativeEnum(re),"Comfy.Graph.ZoomSpeed":c.number(),"Comfy.Group.DoubleClickTitleToEdit":c.boolean(),"Comfy.GroupSelectedNodes.Padding":c.number(),"Comfy.Locale":c.string(),"Comfy.NodeLibrary.Bookmarks":c.array(c.string()),"Comfy.NodeLibrary.Bookmarks.V2":c.array(c.string()),"Comfy.NodeLibrary.BookmarksCustomization":c.record(c.string(),nS),"Comfy.LinkRelease.Action":zo,"Comfy.LinkRelease.ActionShift":zo,"Comfy.ModelLibrary.AutoLoadAll":c.boolean(),"Comfy.ModelLibrary.NameFormat":c.enum(["filename","title"]),"Comfy.NodeSearchBoxImpl.NodePreview":c.boolean(),"Comfy.NodeSearchBoxImpl":c.enum(["default","simple"]),"Comfy.NodeSearchBoxImpl.ShowCategory":c.boolean(),"Comfy.NodeSearchBoxImpl.ShowIdName":c.boolean(),"Comfy.NodeSearchBoxImpl.ShowNodeFrequency":c.boolean(),"Comfy.NodeSuggestions.number":c.number(),"Comfy.Node.BypassAllLinksOnDelete":c.boolean(),"Comfy.Node.Opacity":c.number(),"Comfy.Node.MiddleClickRerouteNode":c.boolean(),"Comfy.Node.ShowDeprecated":c.boolean(),"Comfy.Node.ShowExperimental":c.boolean(),"Comfy.Pointer.ClickBufferTime":c.number(),"Comfy.Pointer.ClickDrift":c.number(),"Comfy.Pointer.DoubleClickTime":c.number(),"Comfy.PreviewFormat":c.string(),"Comfy.PromptFilename":c.boolean(),"Comfy.Sidebar.Location":c.enum(["left","right"]),"Comfy.Sidebar.Size":c.enum(["small","normal"]),"Comfy.Sidebar.UnifiedWidth":c.boolean(),"Comfy.Sidebar.Style":c.enum(["floating","connected"]),"Comfy.SnapToGrid.GridSize":c.number(),"Comfy.TextareaWidget.FontSize":c.number(),"Comfy.TextareaWidget.Spellcheck":c.boolean(),"Comfy.UseNewMenu":c.enum(["Disabled","Top"]),"Comfy.TreeExplorer.ItemPadding":c.number(),"Comfy.Validation.Workflows":c.boolean(),"Comfy.Workflow.SortNodeIdOnSave":c.boolean(),"Comfy.Execution.PreviewMethod":iS,"Comfy.Workflow.WorkflowTabsPosition":c.enum(["Sidebar","Topbar"]),"Comfy.Node.DoubleClickTitleToEdit":c.boolean(),"Comfy.WidgetControlMode":c.enum(["before","after"]),"Comfy.Window.UnloadConfirmation":c.boolean(),"Comfy.NodeBadge.NodeSourceBadgeMode":jt,"Comfy.NodeBadge.NodeIdBadgeMode":jt,"Comfy.NodeBadge.NodeLifeCycleBadgeMode":jt,"Comfy.NodeBadge.ShowApiPricing":c.boolean(),"Comfy.Notification.ShowVersionUpdates":c.boolean(),"Comfy.QueueButton.BatchCountLimit":c.number(),"Comfy.Queue.MaxHistoryItems":c.number(),"Comfy.Queue.History.Expanded":c.boolean(),"Comfy.Keybinding.UnsetBindings":c.array(Ro),"Comfy.Keybinding.NewBindings":c.array(Ro),"Comfy.Extension.Disabled":c.array(c.string()),"Comfy.LinkRenderMode":c.number(),"Comfy.Node.AutoSnapLinkToSlot":c.boolean(),"Comfy.Node.SnapHighlightsNode":c.boolean(),"Comfy.Server.ServerConfigValues":c.record(c.string(),c.any()),"Comfy.Server.LaunchArgs":c.record(c.string(),c.string()),"LiteGraph.Canvas.MaximumFps":c.number(),"Comfy.Workflow.ConfirmDelete":c.boolean(),"Comfy.Workflow.AutoSaveDelay":c.number(),"Comfy.Workflow.AutoSave":c.enum(["off","after delay"]),"Comfy.RerouteBeta":c.boolean(),"LiteGraph.Canvas.MinFontSizeForLOD":c.number(),"Comfy.Canvas.SelectionToolbox":c.boolean(),"LiteGraph.Node.TooltipDelay":c.number(),"LiteGraph.ContextMenu.Scaling":c.boolean(),"LiteGraph.Reroute.SplineOffset":c.number(),"LiteGraph.Canvas.LowQualityRenderingZoomThreshold":c.number(),"Comfy.Toast.DisableReconnectingToast":c.boolean(),"Comfy.Workflow.Persist":c.boolean(),"Comfy.TutorialCompleted":c.boolean(),"Comfy.InstalledVersion":c.string().nullable(),"Comfy.Node.AllowImageSizeDraw":c.boolean(),"Comfy.Minimap.Visible":c.boolean(),"Comfy.Minimap.NodeColors":c.boolean(),"Comfy.Minimap.ShowLinks":c.boolean(),"Comfy.Minimap.ShowGroups":c.boolean(),"Comfy.Minimap.RenderBypassState":c.boolean(),"Comfy.Minimap.RenderErrorState":c.boolean(),"Comfy.Canvas.NavigationMode":c.string(),"Comfy.Canvas.LeftMouseClickBehavior":c.string(),"Comfy.Canvas.MouseWheelScroll":c.string(),"Comfy.VueNodes.Enabled":c.boolean(),"Comfy.VueNodes.AutoScaleLayout":c.boolean(),"Comfy.Assets.UseAssetAPI":c.boolean(),"Comfy.Queue.QPOV2":c.boolean(),"Comfy-Desktop.AutoUpdate":c.boolean(),"Comfy-Desktop.SendStatistics":c.boolean(),"Comfy-Desktop.WindowStyle":c.string(),"Comfy-Desktop.UV.PythonInstallMirror":c.string(),"Comfy-Desktop.UV.PypiInstallMirror":c.string(),"Comfy-Desktop.UV.TorchInstallMirror":c.string(),"Comfy.MaskEditor.BrushAdjustmentSpeed":c.number(),"Comfy.MaskEditor.UseDominantAxis":c.boolean(),"Comfy.Load3D.ShowGrid":c.boolean(),"Comfy.Load3D.BackgroundColor":c.string(),"Comfy.Load3D.LightIntensity":c.number(),"Comfy.Load3D.LightIntensityMaximum":c.number(),"Comfy.Load3D.LightIntensityMinimum":c.number(),"Comfy.Load3D.LightAdjustmentIncrement":c.number(),"Comfy.Load3D.CameraType":c.enum(["perspective","orthographic"]),"Comfy.Load3D.3DViewerEnable":c.boolean(),"Comfy.Load3D.PLYEngine":c.enum(["threejs","fastply","sparkjs"]),"Comfy.Memory.AllowManualUnload":c.boolean(),"pysssss.SnapToGrid":c.boolean(),"VHS.AdvancedPreviews":c.string(),"Comfy.Release.Version":c.string(),"Comfy.Release.Status":c.enum(["skipped","changelog seen","what's new seen"]),"Comfy.Release.Timestamp":c.number(),"Comfy.Templates.SelectedModels":c.array(c.string()),"Comfy.Templates.SelectedUseCases":c.array(c.string()),"Comfy.Templates.SelectedRunsOn":c.array(c.string()),"Comfy.Templates.SortBy":c.enum(["default","recommended","popular","alphabetical","newest","vram-low-to-high","model-size-low-to-high"]),"test.setting":c.any(),"main.sub.setting.name":c.any(),"single.setting":c.any(),"LiteGraph.Node.DefaultPadding":c.boolean(),"LiteGraph.Pointer.TrackpadGestures":c.boolean(),"Comfy.VersionCompatibility.DisableWarnings":c.boolean(),"Comfy.RightSidePanel.IsOpen":c.boolean()});var sS=c.enum(["pending","in_progress","completed","failed","cancelled"]),aS=c.object({filename:c.string(),subfolder:c.string(),type:zn,nodeId:c.string(),mediaType:c.string()}),rS=c.object({prompt_id:c.string().optional(),timestamp:c.number().optional(),node_id:c.string(),node_type:c.string(),executed:c.array(c.string()).optional(),exception_message:c.string(),exception_type:c.string(),traceback:c.array(c.string()),current_inputs:c.unknown(),current_outputs:c.unknown()}).passthrough(),Gn=c.object({id:c.string(),status:sS,create_time:c.number(),execution_start_time:c.number().nullable().optional(),execution_end_time:c.number().nullable().optional(),preview_output:aS.nullable().optional(),outputs_count:c.number().nullable().optional(),execution_error:rS.nullable().optional(),workflow_id:c.string().nullable().optional(),priority:c.number().optional()}).passthrough();const lS=Gn.extend({workflow:c.unknown().optional(),outputs:eS.optional(),update_time:c.number().optional(),execution_status:c.unknown().optional(),execution_meta:c.unknown().optional()}).passthrough();var dS=c.object({offset:c.number(),limit:c.number(),total:c.number(),has_more:c.boolean()});const uS=c.object({jobs:c.array(Gn),pagination:dS}),cS=c.object({extra_data:c.object({extra_pnginfo:c.object({workflow:c.unknown()}).optional()}).optional()});async function Hn(o,e,t=200,n=0){const i=`/jobs?status=${e.join(",")}&limit=${t}&offset=${n}`;try{const s=await o(i);if(!s.ok)return console.error(`[Jobs API] Failed to fetch jobs: ${s.status}`),{jobs:[],total:0,offset:0};const a=uS.parse(await s.json());return{jobs:a.jobs,total:a.pagination.total,offset:n}}catch(s){return console.error("[Jobs API] Error fetching jobs:",s),{jobs:[],total:0,offset:0}}}h(Hn,"fetchJobsRaw");var Bo=1e6;function Jt(o,e){return o.map((t,n)=>({...t,priority:t.priority??e-n}))}h(Jt,"assignPriority");async function pS(o,e=200,t=0){const{jobs:n,total:i}=await Hn(o,["completed","failed","cancelled"],e,t);return Jt(n,i-t)}h(pS,"fetchHistory");async function mS(o){const{jobs:e}=await Hn(o,["in_progress","pending"],200,0),t=e.filter(i=>i.status==="in_progress"),n=e.filter(i=>i.status==="pending");return{Running:Jt(t,Bo+t.length),Pending:Jt(n,Bo+t.length+n.length)}}h(mS,"fetchQueue");async function hS(o,e){try{const t=await o(`/jobs/${encodeURIComponent(e)}`);if(!t.ok){console.warn(`Job not found for prompt ${e}`);return}return lS.parse(await t.json())}catch(t){console.error(`Failed to fetch job detail for prompt ${e}:`,t);return}}h(hS,"fetchJobDetail");async function nI(o){const e=cS.safeParse(o?.workflow);if(!e.success)return;const t=e.data.extra_data?.extra_pnginfo?.workflow;if(t)return await Mi(t,n=>{console.warn("[extractWorkflow] Workflow validation failed:",n)})??void 0}h(nI,"extractWorkflow");var jn=class extends Error{static{h(this,"UnauthorizedError")}};function Vo(o,e,t){Array.isArray(o)?o.push([e,t]):o instanceof Headers?o.set(e,t):o[e]=t}h(Vo,"addHeaderEntry");var qn=class extends Error{static{h(this,"PromptExecutionError")}response;constructor(o){super("Prompt execution failed"),this.response=o}toString(){let o="";typeof this.response.error=="string"?o+=this.response.error:this.response.error&&(o+=this.response.error.message+": "+this.response.error.details);for(const[e,t]of Object.entries(this.response.node_errors??[])){o+=`
|
|
76
|
+
${w}`,e*.5,a+d*.5)}Object.assign(o,{textAlign:s,strokeStyle:i,fillStyle:n})}onClick(){this.current_drag_offset=0}current_drag_offset=0;onDrag(o){if(this.options.read_only)return;const{e}=o,t=Ke(this.options),n=this.options.max-this.options.min,i=n/10,s=n/100,a={delta_x:t,shift:i>t?i-i%t:t,delta_y:s>t?s-s%t:t},r=Math.abs(e.movementY)>Math.abs(e.movementX),l=r?-e.movementY:e.movementX,d=15;this.current_drag_offset+=l;let u=0;this.current_drag_offset>d?(u+=1,this.current_drag_offset-=d):this.current_drag_offset<-d&&(u-=1,this.current_drag_offset+=d);const p=e.shiftKey?a.shift:r?a.delta_y:t,m=u*p,g=pe(this.value+m,this.options.min,this.options.max);g!==this.value&&this.setValue(g,o)}},Cw=class extends B{static{h(this,"LegacyWidget")}drawWidget(o,e){const t=_.NODE_WIDGET_HEIGHT;this.draw?.(o,this.node,e.width,this.y,t,!!e.showText)}onClick(){console.warn("Custom widget wrapper onClick was just called. Handling for third party widgets is done via LGraphCanvas - the mouse callback.")}},Tw=class extends B{static{h(this,"MarkdownWidget")}type="markdown";drawWidget(o,e){const{width:t}=e,{y:n,height:i}=this,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d}=o;o.fillStyle=this.background_color,o.fillRect(15,n,t-30,i),o.strokeStyle=this.outline_color,o.strokeRect(15,n,t-30,i),o.fillStyle=this.text_color,o.font="11px monospace",o.textAlign="center",o.textBaseline="middle";const u=`Markdown: ${ye("widgets.node2only")}`;o.fillText(u,t/2,n+i/2),Object.assign(o,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d})}onClick(o){}},Lw=class extends B{static{h(this,"MultiSelectWidget")}type="multiselect";drawWidget(o,e){const{width:t}=e,{y:n,height:i}=this,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d}=o;o.fillStyle=this.background_color,o.fillRect(15,n,t-30,i),o.strokeStyle=this.outline_color,o.strokeRect(15,n,t-30,i),o.fillStyle=this.text_color,o.font="11px monospace",o.textAlign="center",o.textBaseline="middle";const u=`MultiSelect: ${ye("widgets.node2only")}`;o.fillText(u,t/2,n+i/2),Object.assign(o,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d})}onClick(o){}},Ew=class extends Nn{static{h(this,"NumberWidget")}type="number";get _displayValue(){return this.computedDisabled?"":Number(this.value).toFixed(this.options.precision!==void 0?this.options.precision:3)}canIncrement(){const{max:o}=this.options;return o==null||this.value<o}canDecrement(){const{min:o}=this.options;return o==null||this.value>o}incrementValue(o){this.setValue(this.value+Ke(this.options),o)}decrementValue(o){this.setValue(this.value-Ke(this.options),o)}setValue(o,e){let t=o;this.options.min!=null&&t<this.options.min&&(t=this.options.min),this.options.max!=null&&t>this.options.max&&(t=this.options.max),super.setValue(t,e)}onClick({e:o,node:e,canvas:t}){const n=o.canvasX-e.pos[0],i=this.width||e.size[0],s=n<40?-1:n>i-40?1:0;if(s){this.setValue(this.value+s*Ke(this.options),{e:o,node:e,canvas:t});return}t.prompt("Value",this.value,a=>{const r=di(a);r!==void 0&&this.setValue(r,{e:o,node:e,canvas:t})},o)}onDrag({e:o,node:e,canvas:t}){const n=this.width||e.width,i=o.canvasX-e.pos[0];(i<40||i>n-40)&&i>-3&&i<n+3||this.setValue(this.value+(o.deltaX??0)*Ke(this.options),{e:o,node:e,canvas:t})}},Nw=class extends B{static{h(this,"SelectButtonWidget")}type="selectbutton";drawWidget(o,e){const{width:t}=e,{y:n,height:i}=this,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d}=o;o.fillStyle=this.background_color,o.fillRect(15,n,t-30,i),o.strokeStyle=this.outline_color,o.strokeRect(15,n,t-30,i),o.fillStyle=this.text_color,o.font="11px monospace",o.textAlign="center",o.textBaseline="middle";const u=`SelectButton: ${ye("widgets.node2only")}`;o.fillText(u,t/2,n+i/2),Object.assign(o,{fillStyle:s,strokeStyle:a,textAlign:r,textBaseline:l,font:d})}onClick(o){}},xw=class extends B{static{h(this,"SliderWidget")}type="slider";marker;drawWidget(o,{width:e,showText:t=!0}){const{fillStyle:n,strokeStyle:i,textAlign:s}=o,{height:a,y:r}=this,{margin:l}=B;o.fillStyle=this.background_color,o.fillRect(l,r,e-l*2,a);const d=this.options.max-this.options.min;let u=(this.value-this.options.min)/d;if(u=pe(u,0,1),o.fillStyle=this.options.slider_color??"#678",o.fillRect(l,r,u*(e-l*2),a),t&&!this.computedDisabled&&(o.strokeStyle=this.outline_color,o.strokeRect(l,r,e-l*2,a)),this.marker!=null){let p=(this.marker-this.options.min)/d;p=pe(p,0,1),o.fillStyle=this.options.marker_color??"#AA9",o.fillRect(l+p*(e-l*2),r,2,a)}if(t){o.textAlign="center",o.fillStyle=this.text_color;const p=Number(this.value).toFixed(this.options.precision??3);o.fillText(`${this.label||this.name} ${p}`,e*.5,r+a*.7)}Object.assign(o,{textAlign:s,strokeStyle:i,fillStyle:n})}onClick(o){if(this.options.read_only)return;const{e,node:t}=o,n=this.width||t.size[0],i=pe((e.canvasX-t.pos[0]-15)/(n-30),0,1),s=this.options.min+(this.options.max-this.options.min)*i;s!==this.value&&this.setValue(s,o)}onDrag(o){if(this.options.read_only)return!1;const{e,node:t}=o,n=this.width||t.size[0],i=pe((e.canvasX-t.pos[0]-15)/(n-30),0,1),s=this.options.min+(this.options.max-this.options.min)*i;s!==this.value&&this.setValue(s,o)}},xo=class extends B{static{h(this,"TextWidget")}constructor(o,e){super(o,e),this.type??="string",this.value=o.value?.toString()??""}drawWidget(o,{width:e,showText:t=!0}){const{fillStyle:n,strokeStyle:i,textAlign:s}=o;this.drawWidgetShape(o,{width:e,showText:t}),t&&this.drawTruncatingText({ctx:o,width:e,leftPadding:0,rightPadding:0}),Object.assign(o,{textAlign:s,strokeStyle:i,fillStyle:n})}onClick({e:o,node:e,canvas:t}){t.prompt("Value",this.value,n=>{n!==null&&this.setValue(n,{e:o,node:e,canvas:t})},o,this.options?.multiline??!1)}},Aw=class extends B{static{h(this,"TextareaWidget")}type="textarea";drawWidget(o,e){this.drawVueOnlyWarning(o,e,"Textarea")}onClick(o){}},Dw=class extends B{static{h(this,"TreeSelectWidget")}type="treeselect";drawWidget(o,e){this.drawVueOnlyWarning(o,e,"TreeSelect")}onClick(o){}};function Ct(o,e,t=!0){if(o instanceof B)return o;const n=o;switch(n.type){case"button":return U(fw,n,e);case"toggle":return U(hw,n,e);case"slider":return U(xw,n,e);case"knob":return U(Iw,n,e);case"combo":return U(bw,n,e);case"number":return U(Ew,n,e);case"string":return U(xo,n,e);case"text":return U(xo,n,e);case"fileupload":return U(vw,n,e);case"color":return U(yw,n,e);case"markdown":return U(Tw,n,e);case"treeselect":return U(Dw,n,e);case"multiselect":return U(Lw,n,e);case"chart":return U(_w,n,e);case"galleria":return U(kw,n,e);case"imagecompare":return U(ww,n,e);case"selectbutton":return U(Nw,n,e);case"textarea":return U(Aw,n,e);case"asset":return U(En,n,e);case"imagecrop":return U(Sw,n,e);case"boundingbox":return U(gw,n,e);default:if(t)return U(Cw,o,e)}}h(Ct,"toConcreteWidget");function eI(o){return o.type==="combo"}h(eI,"isComboWidget");function tI(o){return o.type==="asset"}h(tI,"isAssetWidget");var q=class Qe{static{h(this,"LGraphNode")}static title;static MAX_CONSOLE;static type;static category;static description;static filter;static skip_list;static resizeHandleSize=15;static resizeEdgeSize=5;static keepAllLinksOnBypass=!1;title;get titleFontStyle(){return`${_.NODE_TEXT_SIZE}px ${_.NODE_FONT}`}get innerFontStyle(){return`normal ${_.NODE_SUBTEXT_SIZE}px ${_.NODE_FONT}`}get displayType(){return this.type}graph=null;id;type="";inputs=[];outputs=[];#e=[];#t=[];properties={};properties_info=[];flags={};widgets;changeTracker;freeWidgetSpace;locked;order=0;mode=H.ALWAYS;last_serialization;serialize_widgets;color;bgcolor;boxcolor;get renderingColor(){return uo(this.color||this.constructor.color||_.NODE_DEFAULT_COLOR,{lightness:_.nodeLightness})}get renderingBgColor(){const e=this.bgcolor||this.constructor.bgcolor||_.NODE_DEFAULT_BGCOLOR,t={opacity:_.nodeOpacity,lightness:_.nodeLightness};return uo(this.mode===H.BYPASS?_.NODE_DEFAULT_BYPASS_COLOR:e,t)}get renderingBoxColor(){if(this.boxcolor)return this.boxcolor;if(_.node_box_coloured_when_on){if(this.action_triggered)return"#FFF";if(this.execute_triggered)return"#AAA"}if(_.node_box_coloured_by_mode){const e=_.NODE_MODES_COLORS[this.mode??H.ALWAYS];if(e)return e}return _.NODE_DEFAULT_BOXCOLOR}setColorOption(e){e==null?(this.color=void 0,this.bgcolor=void 0):(this.color=e.color,this.bgcolor=e.bgcolor)}getColorOption(){return Object.values(ce.node_colors).find(e=>e.color===this.color&&e.bgcolor===this.bgcolor)??null}strokeStyles;progress;exec_version;action_call;execute_triggered;action_triggered;widgets_up;widgets_start_y;lostFocusAt;gotFocusAt;badges=[];title_buttons=[];badgePosition=So.TopLeft;_collapsed_width;console;_level;_shape;mouseOver;redraw_on_mouse;resizable;clonable;_relative_id;clip_area;ignore_remove;has_errors;removable;block_delete;selected;showAdvanced;isSubgraphNode(){return!1}#o=new X;get renderArea(){return this.#o}#n=new X;get boundingRect(){return this.#n}get boundingOffset(){const{pos:[e,t],boundingRect:[n,i]}=this;return[e-n,t-i]}_posSize=new X;_pos=this._posSize.pos;_size=this._posSize.size;get pos(){return this._pos}set pos(e){!e||e.length<2||(this._pos[0]=e[0],this._pos[1]=e[1])}get size(){return this._size}set size(e){!e||e.length<2||(this._size[0]=e[0],this._size[1]=e[1])}get renderingSize(){return this.flags.collapsed?[this._collapsed_width??0,0]:this._size}get shape(){return this._shape}set shape(e){const t=this._shape;switch(e){case"default":this._shape=void 0;break;case"box":this._shape=M.BOX;break;case"round":this._shape=M.ROUND;break;case"circle":this._shape=M.CIRCLE;break;case"card":this._shape=M.CARD;break;default:this._shape=e}t!==this._shape&&this.graph?.trigger("node:property:changed",{nodeId:this.id,property:"shape",oldValue:t,newValue:this._shape})}get renderingShape(){return this._shape||this.constructor.shape||_.NODE_DEFAULT_SHAPE}get is_selected(){return this.selected}set is_selected(e){this.selected=e}get title_mode(){return this.constructor.title_mode??se.NORMAL_TITLE}#s(){if(this.has_errors)return{padding:12,lineWidth:10,color:_.NODE_ERROR_COLOUR}}#i(){if(this.selected)return{padding:this.has_errors?20:void 0}}constructor(e,t){this.id=_.use_uuids?_.uuidv4():-1,this.title=e||"Unnamed",this.type=t??"",this.size=[_.NODE_WIDTH,60],this.pos=[10,10],this.strokeStyles={error:this.#s,selected:this.#i},this.changeTracker=new hs(this)}configure(e){this.graph&&this.graph._version++;for(const t in e){if(t=="properties"){for(const n in e.properties)this.properties[n]=e.properties[n],this.onPropertyChanged?.(n,e.properties[n]);continue}e[t]!=null&&(typeof e[t]=="object"?this[t]?.configure?this[t]?.configure(e[t]):this[t]=_.cloneObject(e[t],this[t]):this[t]=e[t])}e.title||(this.title=this.constructor.title),this.inputs??=[],this.inputs=this.inputs.map(t=>U(Be,t,this));for(const[t,n]of this.inputs.entries()){const i=this.graph&&n.link!=null?this.graph._links.get(n.link):null;this.onConnectionsChange?.(j.INPUT,t,!0,i,n),this.onInputAdded?.(n)}this.outputs??=[],this.outputs=this.outputs.map(t=>U(mt,t,this));for(const[t,n]of this.outputs.entries())if(n.links){for(const i of n.links){const s=this.graph?this.graph._links.get(i):null;this.onConnectionsChange?.(j.OUTPUT,t,!0,s,n)}this.onOutputAdded?.(n)}if(this._internalConfigureAfterSlots?.(),this.widgets){for(const t of this.widgets){if(!t)continue;const n=this.inputs.find(i=>i.widget?.name===t.name);n?.label&&(t.label=n.label),t.options?.property&&this.properties[t.options.property]!=null&&(t.value=JSON.parse(JSON.stringify(this.properties[t.options.property])))}if(e.widgets_values){let t=0;for(const n of this.widgets??[])if(n.serialize!==!1){if(t>=e.widgets_values.length)break;n.value=e.widgets_values[t++]}}}this.pinned&&(this.resizable=!1),this.onConfigure?.(e)}serialize(){const e={id:this.id,type:this.type,pos:[this.pos[0],this.pos[1]],size:[this.size[0],this.size[1]],flags:_.cloneObject(this.flags),order:this.order,mode:this.mode,showAdvanced:this.showAdvanced};if(this.constructor===Qe&&this.last_serialization)return{...this.last_serialization,mode:e.mode,pos:e.pos};this.inputs&&(e.inputs=this.inputs.map(n=>Zi(n))),this.outputs&&(e.outputs=this.outputs.map(n=>Ji(n))),this.title&&this.title!=this.constructor.title&&(e.title=this.title),this.properties&&(e.properties=_.cloneObject(this.properties));const{widgets:t}=this;if(t&&this.serialize_widgets){e.widgets_values=[];for(const[n,i]of t.entries())i.serialize!==!1&&(e.widgets_values[n]=i?i.value:null)}return!e.type&&this.constructor.type&&(e.type=this.constructor.type),this.color&&(e.color=this.color),this.bgcolor&&(e.bgcolor=this.bgcolor),this.boxcolor&&(e.boxcolor=this.boxcolor),this.shape&&(e.shape=this.shape),this.onSerialize?.(e)&&console.warn("node onSerialize shouldn't return anything, data should be stored in the object pass in the first parameter"),e}clone(){if(this.type==null)return null;const e=_.createNode(this.type);if(!e)return null;const t=_.cloneObject(this.serialize()),{inputs:n,outputs:i}=t;if(n)for(const s of n)s.link=null;if(i)for(const{links:s}of i)s&&(s.length=0);return t.id=void 0,_.use_uuids&&(t.id=_.uuidv4()),e.configure(t),e}toString(){return JSON.stringify(this.serialize())}getTitle(){return this.title||this.constructor.title}setProperty(e,t){if(this.properties||={},t===this.properties[e])return;const n=this.properties[e];if(this.properties[e]=t,this.onPropertyChanged?.(e,t,n)===!1&&(this.properties[e]=n),this.widgets){for(const i of this.widgets)if(i&&i.options.property==e){i.value=t;break}}}setOutputData(e,t){const{outputs:n}=this;if(!n||e==-1||e>=n.length)return;const i=n[e];if(!i)return;if(i._data=t,!this.graph)throw new N;const{links:s}=n[e];if(s)for(const a of s){const r=this.graph._links.get(a);r&&(r.data=t)}}setOutputDataType(e,t){const{outputs:n}=this;if(!n||e==-1||e>=n.length)return;const i=n[e];if(!i)return;if(i.type=t,!this.graph)throw new N;const{links:s}=n[e];if(s)for(const a of s){const r=this.graph._links.get(a);r&&(r.type=t)}}getInputData(e,t){if(!this.inputs||e>=this.inputs.length||this.inputs[e].link==null)return;if(!this.graph)throw new N;const n=this.inputs[e].link,i=this.graph._links.get(n);if(!i)return null;if(!t)return i.data;const s=this.graph.getNodeById(i.origin_id);return s&&(s.updateOutputData?s.updateOutputData(i.origin_slot):s.onExecute?.()),i.data}getInputDataType(e){if(!this.inputs||e>=this.inputs.length||this.inputs[e].link==null)return null;if(!this.graph)throw new N;const t=this.inputs[e].link,n=this.graph._links.get(t);if(!n)return null;const i=this.graph.getNodeById(n.origin_id);if(!i)return n.type;const s=i.outputs[n.origin_slot];return s?s.type:null}getInputDataByName(e,t){const n=this.findInputSlot(e);return n==-1?null:this.getInputData(n,t)}isInputConnected(e){return this.inputs?e<this.inputs.length&&this.inputs[e].link!=null:!1}getInputInfo(e){return!this.inputs||!(e<this.inputs.length)?null:this.inputs[e]}getInputLink(e){if(!this.inputs)return null;if(e<this.inputs.length){if(!this.graph)throw new N;const t=this.inputs[e];if(t.link!=null)return this.graph._links.get(t.link)??null}return null}getInputNode(e){if(!this.inputs||e>=this.inputs.length)return null;const t=this.inputs[e];if(!t||t.link===null)return null;if(!this.graph)throw new N;const n=this.graph._links.get(t.link);return n?this.graph.getNodeById(n.origin_id):null}getInputOrProperty(e){const{inputs:t}=this;if(!t?.length)return this.properties?this.properties[e]:null;if(!this.graph)throw new N;for(const n of t)if(e==n.name&&n.link!=null){const i=this.graph._links.get(n.link);if(i)return i.data}return this.properties[e]}getOutputData(e){return!this.outputs||e>=this.outputs.length?null:this.outputs[e]._data}getOutputInfo(e){return!this.outputs||!(e<this.outputs.length)?null:this.outputs[e]}isOutputConnected(e){return this.outputs?e<this.outputs.length&&Number(this.outputs[e].links?.length)>0:!1}isAnyOutputConnected(){const{outputs:e}=this;if(!e)return!1;for(const t of e)if(t.links?.length)return!0;return!1}getOutputNodes(e){const{outputs:t}=this;if(!t||t.length==0||e>=t.length)return null;const{links:n}=t[e];if(!n||n.length==0)return null;if(!this.graph)throw new N;const i=[];for(const s of n){const a=this.graph._links.get(s);if(a){const r=this.graph.getNodeById(a.target_id);r&&i.push(r)}}return i}addOnTriggerInput(){const e=this.findInputSlot("onTrigger");return e==-1?(this.addInput("onTrigger",_.EVENT,{nameLocked:!0}),this.findInputSlot("onTrigger")):e}addOnExecutedOutput(){const e=this.findOutputSlot("onExecuted");return e==-1?(this.addOutput("onExecuted",_.ACTION,{nameLocked:!0}),this.findOutputSlot("onExecuted")):e}onAfterExecuteNode(e,t){const n=this.findOutputSlot("onExecuted");n!=-1&&this.triggerSlot(n,e,null,t)}changeMode(e){switch(e){case H.ON_EVENT:break;case H.ON_TRIGGER:this.addOnTriggerInput(),this.addOnExecutedOutput();break;case H.NEVER:break;case H.ALWAYS:break;case _.ON_REQUEST:break;default:return!1}return this.mode=e,!0}doExecute(e,t){if(t=t||{},this.onExecute){if(t.action_call||=`${this.id}_exec_${Math.floor(Math.random()*9999)}`,!this.graph)throw new N;this.graph.nodes_executing[this.id]=!0,this.onExecute(e,t),this.graph.nodes_executing[this.id]=!1,this.exec_version=this.graph.iteration,t?.action_call&&(this.action_call=t.action_call,this.graph.nodes_executedAction[this.id]=t.action_call)}this.execute_triggered=2,this.onAfterExecuteNode?.(e,t)}actionDo(e,t,n){if(n=n||{},this.onAction){if(n.action_call||=`${this.id}_${e||"action"}_${Math.floor(Math.random()*9999)}`,!this.graph)throw new N;this.graph.nodes_actioning[this.id]=e||"actioning",this.onAction(e,t,n),this.graph.nodes_actioning[this.id]=!1,n?.action_call&&(this.action_call=n.action_call,this.graph.nodes_executedAction[this.id]=n.action_call)}this.action_triggered=2,this.onAfterExecuteNode?.(t,n)}trigger(e,t,n){const{outputs:i}=this;if(!(!i||!i.length)){this.graph&&(this.graph._last_trigger_time=_.getTime());for(const[s,a]of i.entries())!a||a.type!==_.EVENT||e&&a.name!=e||this.triggerSlot(s,t,null,n)}}triggerSlot(e,t,n,i){if(i=i||{},!this.outputs)return;if(e==null){console.error("slot must be a number");return}typeof e!="number"&&console.warn("slot must be a number, use node.trigger('name') if you want to use a string");const s=this.outputs[e];if(!s)return;const a=s.links;if(!(!a||!a.length)){if(!this.graph)throw new N;this.graph._last_trigger_time=_.getTime();for(const r of a){if(n!=null&&n!=r)continue;const l=this.graph._links.get(r);if(!l)continue;l._last_time=_.getTime();const d=this.graph.getNodeById(l.target_id);if(d){if(d.mode===H.ON_TRIGGER)i.action_call||(i.action_call=`${this.id}_trigg_${Math.floor(Math.random()*9999)}`),d.doExecute?.(t,i);else if(d.onAction){i.action_call||(i.action_call=`${this.id}_act_${Math.floor(Math.random()*9999)}`);const u=d.inputs[l.target_slot];d.actionDo(u.name,t,i)}}}}}clearTriggeredSlot(e,t){if(!this.outputs)return;const n=this.outputs[e];if(!n)return;const i=n.links;if(!(!i||!i.length)){if(!this.graph)throw new N;for(const s of i){if(t!=null&&t!=s)continue;const a=this.graph._links.get(s);a&&(a._last_time=0)}}}setSize(e){this.size=e,this.onResize?.(this.size)}expandToFitContent(){const e=this.computeSize();this.setSize([Math.max(this.size[0],e[0]),Math.max(this.size[1],e[1])])}addProperty(e,t,n,i){const s={name:e,type:n,default_value:t};return i&&Object.assign(s,i),this.properties_info||=[],this.properties_info.push(s),this.properties||={},this.properties[e]=t,s}addOutput(e,t,n){const i=Object.assign(new mt({name:e,type:t,links:null},this),n);return this.outputs||=[],this.outputs.push(i),this.onOutputAdded?.(i),_.auto_load_slot_types&&_.registerNodeAndSlotType(this,t,!0),this.expandToFitContent(),this.setDirtyCanvas(!0,!0),i}removeOutput(e){this.graph&&this.disconnectOutput(e);const{outputs:t}=this;t.splice(e,1);for(let n=e;n<t.length;++n){const i=t[n];if(!(!i||!i.links)&&this.graph)for(const s of i.links){const a=this.graph._links.get(s);a&&a.origin_slot--}}this.onOutputRemoved?.(e),this.setDirtyCanvas(!0,!0)}addInput(e,t,n){t||=0;const i=Object.assign(new Be({name:e,type:t,link:null},this),n);return this.inputs||=[],this.inputs.push(i),this.expandToFitContent(),this.onInputAdded?.(i),_.registerNodeAndSlotType(this,t),this.setDirtyCanvas(!0,!0),i}removeInput(e){this.graph&&this.disconnectInput(e,!0);const{inputs:t}=this,n=t.splice(e,1);for(let i=e;i<t.length;++i){const s=t[i];if(s?.link&&this.graph){const a=this.graph._links.get(s.link);a&&a.target_slot--}}this.onInputRemoved?.(e,n[0]),this.setDirtyCanvas(!0,!0)}computeSize(e){const t=this.constructor.size;if(t)return[t[0],t[1]];const{inputs:n,outputs:i,widgets:s}=this;let a=Math.max(n?n.filter(C=>!we(C)).length:1,i?i.length:1);const r=e??[0,0];a=Math.max(a,1);const l=_.NODE_TEXT_SIZE,d=_.NODE_TITLE_HEIGHT,u=d*.33,p=d+E(this.title,this.titleFontStyle)+u;let m=0,g=0,f=0;if(n)for(const C of n){const I=E(C.label||C.localized_name||C.name||"",this.innerFontStyle);if(we(C)){const P=this.getWidgetFromSlot(C);if(P&&!this.isWidgetVisible(P))continue;I>g&&(g=I)}else I>m&&(m=I)}if(i)for(const C of i){const I=E(C.label||C.localized_name||C.name||"",this.innerFontStyle);f<I&&(f=I)}const y=_.NODE_WIDTH*(s?.length?1.5:1),b=m&&f?5:0,v=m+f+2*_.NODE_SLOT_HEIGHT+b,k=B.margin+B.arrowMargin+B.arrowWidth,w=B.minValueWidth+2*k;g&&(g+=w),r[0]=Math.max(v,g,p,y),r[1]=(this.constructor.slot_start_y||0)+a*_.NODE_SLOT_HEIGHT;let S=0;if(s?.length){for(const C of s){if(!this.isWidgetVisible(C))continue;let I=0;if(C.computeSize)I+=C.computeSize(r[0])[1];else if(C.computeLayoutSize){const{minHeight:P,minWidth:A}=C.computeLayoutSize(this),F=A+w;F>r[0]&&(r[0]=F),I+=P}else I+=_.NODE_WIDGET_HEIGHT;S+=I+4}S+=8}this.widgets_up?r[1]=Math.max(r[1],S):this.widgets_start_y!=null?r[1]=Math.max(r[1],S+this.widgets_start_y):r[1]+=S;function E(C,I){return ce._measureText?.(C,I)??l*(C?.length??0)*.6}return h(E,"compute_text_size"),this.constructor.min_height&&r[1]<this.constructor.min_height&&(r[1]=this.constructor.min_height),r[1]+=6,r}inResizeCorner(e,t){const n=this.outputs?this.outputs.length:1,i=(this.constructor.slot_start_y||0)+n*_.NODE_SLOT_HEIGHT;return G(e,t,this.pos[0]+this.size[0]-15,this.pos[1]+Math.max(this.size[1]-15,i),20,20)}findResizeDirection(e,t){if(this.resizable===!1)return;const{boundingRect:n}=this;if(n.containsXy(e,t))return n.findContainingCorner(e,t,Qe.resizeHandleSize)}getPropertyInfo(e){let t=null;const{properties_info:n}=this;if(n){for(const i of n)if(i.name==e){t=i;break}}return this.constructor[`@${e}`]&&(t=this.constructor[`@${e}`]),this.constructor.widgets_info?.[e]&&(t=this.constructor.widgets_info[e]),!t&&this.onGetPropertyInfo&&(t=this.onGetPropertyInfo(e)),t||={},t.type||=typeof this.properties[e],t.widget=="combo"&&(t.type="enum"),t}addWidget(e,t,n,i,s){this.widgets||=[],!s&&i&&typeof i=="object"&&(s=i,i=null),s||={},typeof s=="string"&&(s={property:s}),i&&typeof i=="string"&&(s.property=i,i=null);const a={type:e.toLowerCase(),name:t,value:n,callback:typeof i!="function"?void 0:i,options:s,y:0};if(a.options.y!==void 0&&(a.y=a.options.y),!i&&!a.options.callback&&!a.options.property&&console.warn("LiteGraph addWidget(...) without a callback or property assigned"),e=="combo"&&!a.options.values)throw"LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }";const r=this.addCustomWidget(a);return this.expandToFitContent(),r}addCustomWidget(e){this.widgets||=[];const t=Ct(e,this,!1)??e;return this.widgets.push(t),t}addTitleButton(e){this.title_buttons||=[];const t=new bs(e);return this.title_buttons.push(t),t}onTitleButtonClick(e,t){t.dispatch("litegraph:node-title-button-clicked",{node:this,button:e})}removeWidgetByName(e){const t=this.widgets?.find(n=>n.name===e);t&&this.removeWidget(t)}removeWidget(e){if(!this.widgets)throw new Error("removeWidget called on node without widgets");const t=this.widgets.indexOf(e);if(t===-1)throw new Error("Widget not found on this node");if(this.inputs)for(const n of this.inputs)n._widget===e&&(n._widget=void 0,n.widget=void 0);e.onRemove?.(),this.widgets.splice(t,1)}ensureWidgetRemoved(e){try{this.removeWidget(e)}catch(t){console.error("Failed to remove widget",t)}}move(e,t){this.pinned||_.vueNodesMode||(this.pos[0]+=e,this.pos[1]+=t)}measure(e,t){const n=this.title_mode,i=n!=se.TRANSPARENT_TITLE&&n!=se.NO_TITLE?_.NODE_TITLE_HEIGHT:0;e[0]=this.pos[0],e[1]=this.pos[1]+-i,this.flags?.collapsed?(t&&(t.font=this.innerFontStyle),this._collapsed_width=Math.min(this.size[0],t?t.measureText(this.getTitle()??"").width+_.NODE_TITLE_HEIGHT*2:0),e[2]=this._collapsed_width||_.NODE_COLLAPSED_WIDTH,e[3]=_.NODE_TITLE_HEIGHT):(e[2]=this.size[0],e[3]=this.size[1]+i)}getBounding(e,t){e||=[0,0,0,0];const n=t?this.renderArea:this.boundingRect;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e}updateArea(e){const t=this.#n;this.measure(t,e),this.onBounding?.(t);const n=this.#o;n.set(t),n[0]-=4,n[1]-=4,n[2]+=10,n[3]+=9}isPointInside(e,t){return yt(e,t,this.boundingRect)}isPointInCollapse(e,t){const n=_.NODE_TITLE_HEIGHT;return G(e,t,this.pos[0],this.pos[1]-n,n,n)}getInputOnPos(e){return mn(this,e[0],e[1])?.input}getOutputOnPos(e){return hn(this,e[0],e[1])?.output}getSlotOnPos(e){if(We(e,this.boundingRect))return this.getInputOnPos(e)??this.getOutputOnPos(e)}getSlotInPosition(e,t){const{inputs:n,outputs:i}=this;if(n)for(const[s,a]of n.entries()){const r=this.getInputPos(s);if(G(e,t,r[0]-10,r[1]-10,20,20))return{input:a,slot:s,link_pos:r}}if(i)for(const[s,a]of i.entries()){const r=this.getOutputPos(s);if(G(e,t,r[0]-10,r[1]-10,20,20))return{output:a,slot:s,link_pos:r}}return null}getWidgetOnPos(e,t,n=!1){const{widgets:i,pos:s,size:a}=this;if(!i?.length)return;const r=e-s[0],l=t-s[1],d=a[0];for(const u of i){if(u.computedDisabled&&!n||!this.isWidgetVisible(u))continue;const p=u.computedHeight??u.computeSize?.(d)[1]??_.NODE_WIDGET_HEIGHT,m=u,g=m.margin??-2,f=m.margin??2,y=m.margin??6,b=u.width||d;if(u.last_y!==void 0&&G(r,l,y,u.last_y+g,b-2*y,p-g-f))return u}}findInputSlot(e,t=!1){const{inputs:n}=this;if(!n)return-1;for(const[i,s]of n.entries())if(e==s.name)return t?s:i;return-1}findOutputSlot(e,t=!1){const{outputs:n}=this;if(!n)return-1;for(const[i,s]of n.entries())if(e==s.name)return t?s:i;return-1}findInputSlotFree(e){return this.#d(this.inputs,e)}findOutputSlotFree(e){return this.#d(this.outputs,e)}#d(e,t){const n=Object.assign({returnObj:!1,typesNotAccepted:[]},t||{}),i=e?.length;if(!(i>0))return-1;for(let s=0;s<i;++s){const a=e[s];if(!(!a||a.link||a.links?.length)&&!n.typesNotAccepted?.includes?.(a.type))return n.returnObj?a:s}return-1}findInputSlotByType(e,t,n,i){return this.#a(this.inputs,e,t,n,i)}findOutputSlotByType(e,t,n,i){return this.#a(this.outputs,e,t,n,i)}findSlotByType(e,t,n,i,s){return e?this.#a(this.inputs,t,n,i,s):this.#a(this.outputs,t,n,i,s)}#a(e,t,n,i,s){const a=e?.length;if(!a)return-1;(t==""||t=="*")&&(t=0);const r=String(t).toLowerCase().split(",");let l=null;for(let d=0;d<a;++d){const u=e[d],p=u.type=="0"||u.type=="*"?["0"]:String(u.type).toLowerCase().split(",");for(const m of r){const g=m=="_event_"?_.EVENT:m;for(const f of p){const y=f=="_event_"?_.EVENT:f;if(g==y||g==="*"||y==="*"){if(i&&(u.links?.length||u.link!=null)){l??=n?u:d;continue}return n?u:d}}}}return s?-1:l??-1}findConnectByTypeSlot(e,t,n,i){i&&typeof i=="object"&&("firstFreeIfInputGeneralInCase"in i&&(i.wildcardToTyped=!!i.firstFreeIfInputGeneralInCase),"firstFreeIfOutputGeneralInCase"in i&&(i.wildcardToTyped=!!i.firstFreeIfOutputGeneralInCase),"generalTypeInCase"in i&&(i.typedToWildcard=!!i.generalTypeInCase));const s=Object.assign({createEventInCase:!0,wildcardToTyped:!0,typedToWildcard:!0},i);if(!this.graph)throw new N;if(t&&typeof t=="number"){const r=this.graph.getNodeById(t);if(!r)return;t=r}const a=t.findSlotByType(e,n,!1,!0);if(a>=0&&a!==null)return a;if(s.createEventInCase&&n==_.EVENT){if(e)return-1;if(_.do_add_triggers_slots)return t.addOnExecutedOutput()}if(s.typedToWildcard){const r=t.findSlotByType(e,0,!1,!0,!0);if(r>=0)return r}if(s.wildcardToTyped&&(n==0||n=="*"||n=="")){const r={typesNotAccepted:[_.EVENT]},l=e?t.findInputSlotFree(r):t.findOutputSlotFree(r);if(l>=0)return l}}findOutputByType(e){return vt(this.outputs,e,t=>!t.links?.length)}findInputByType(e){return vt(this.inputs,e,t=>t.link==null||!!this.graph?.getLink(t.link)?._dragging)}connectByType(e,t,n,i){const s=this.findConnectByTypeSlot(!0,t,n,i);return s!==void 0?this.connect(e,t,s,i?.afterRerouteId):null}connectByTypeOutput(e,t,n,i){typeof i=="object"&&("firstFreeIfInputGeneralInCase"in i&&(i.wildcardToTyped=!!i.firstFreeIfInputGeneralInCase),"generalTypeInCase"in i&&(i.typedToWildcard=!!i.generalTypeInCase));const s=this.findConnectByTypeSlot(!1,t,n,i);return s!==void 0?t.connect(s,this,e,i?.afterRerouteId):(console.error("[connectByType]: no way to connect type:",n,"to node:",t),null)}canConnectTo(e,t,n){return this.id!==e.id&&_.isValidConnection(n.type,t.type)}connect(e,t,n,i){let s;const{graph:a,outputs:r}=this;if(!a)return console.error("Connect: Error, node doesn't belong to any graph. Nodes must be added first to a graph before connecting them."),null;if(typeof e=="string"){if(e=this.findOutputSlot(e),e==-1)return _.debug&&console.error(`Connect: Error, no slot of name ${e}`),null}else if(!r||e>=r.length)return _.debug&&console.error("Connect: Error, slot number not found"),null;if(t&&typeof t=="number"){const u=a.getNodeById(t);if(!u)throw"target node is null";t=u}if(!t)throw"target node is null";if(t==this)return null;if(typeof n=="string"){if(s=t.findInputSlot(n),s==-1)return _.debug&&console.error(`Connect: Error, no slot of name ${s}`),null}else if(n===_.EVENT)if(_.do_add_triggers_slots)t.changeMode(H.ON_TRIGGER),s=t.findInputSlot("onTrigger");else return null;else typeof n=="number"?s=n:s=0;if(t.onBeforeConnectInput){const u=t.onBeforeConnectInput(s,n);s=typeof u=="number"?u:null}if(s===null||!t.inputs||s>=t.inputs.length)return _.debug&&console.error("Connect: Error, slot number not found"),null;const l=t.inputs[s],d=r[e];return d?(d.links?.length&&d.type===_.EVENT&&!_.allow_multi_output_for_events&&(a.beforeChange(),this.disconnectOutput(e)),this.connectSlots(d,t,l,i)??null):null}connectSlots(e,t,n,i){const{graph:s}=this;if(!s)throw new N;const a=Ae(),r=this.outputs.indexOf(e);if(r===-1){console.warn("connectSlots: output not found");return}const l=t.inputs.indexOf(n);if(l===-1){console.warn("connectSlots: input not found");return}if(!_.isValidConnection(e.type,n.type))return this.setDirtyCanvas(!1,!0),null;if(t.onConnectInput?.(l,e.type,e,this,r)===!1||this.onConnectOutput?.(r,n.type,n,t,l)===!1)return null;t.inputs[l]?.link!=null&&(s.beforeChange(),t.disconnectInput(l,!0));const d=n.type&&e.type&&gs(n.type,e.type),u=new z(++s.state.lastLinkId,d||n.type||e.type,this.id,r,t.id,l,i);s._links.set(u.id,u),a.setSource(ue.Canvas),a.createLink(u.id,this.id,r,t.id,l),e.links??=[],e.links.push(u.id);const p=t.inputs[l];p.link=u.id,p.widget&&s.trigger("node:slot-links:changed",{nodeId:t.id,slotType:j.INPUT,slotIndex:l,connected:!0,linkId:u.id});const m=z.getReroutes(s,u);for(const f of m)f.linkIds.add(u.id),f.floating&&(f.floating=void 0),f._dragging=void 0;const g=m.at(-1);if(g)for(const f of g.floatingLinkIds){const y=s.floatingLinks.get(f);y?.parentId===g.id&&s.removeFloatingLink(y)}return s._version++,this.onConnectionsChange?.(j.OUTPUT,r,!0,u,e),t.onConnectionsChange?.(j.INPUT,l,!0,u,n),this.setDirtyCanvas(!1,!0),s.afterChange(),u}connectFloatingReroute(e,t,n){const{graph:i,id:s}=this;if(!i)throw new N;const a=this.inputs.indexOf(t),r=this.outputs.indexOf(t);if(a===-1&&r===-1)throw new Error("Invalid slot");const l=r===-1?"input":"output",d=i.setReroute({pos:e,parentId:n,linkIds:[],floating:{slotType:l}}),u=i.getReroute(n),p=u?.floating?.slotType==="output";if(n==null||!p){const g=new z(-1,t.type,r===-1?-1:s,r,a===-1?-1:s,a);return g.parentId=d.id,i.addFloatingLink(g),d}if(!u)throw new Error("[connectFloatingReroute] Parent reroute not found");const m=u.getFloatingLinks("output")?.[0];if(!m)throw new Error("[connectFloatingReroute] Floating link not found");return d.floatingLinkIds.add(m.id),m.parentId=d.id,u.floating=void 0,d}disconnectOutput(e,t){if(typeof e=="string"){if(e=this.findOutputSlot(e),e==-1)return _.debug&&console.error(`Connect: Error, no slot of name ${e}`),!1}else if(!this.outputs||e>=this.outputs.length)return _.debug&&console.error("Connect: Error, slot number not found"),!1;const n=this.outputs[e];if(!n)return!1;if(n._floatingLinks)for(const a of n._floatingLinks)a.hasOrigin(this.id,e)&&this.graph?.removeFloatingLink(a);if(!n.links||n.links.length==0)return!1;const{links:i}=n,s=this.graph;if(!s)throw new N;if(t){const a=typeof t=="number"?s.getNodeById(t):t;if(!a)throw"Target Node not found";for(const[r,l]of i.entries()){const d=s._links.get(l);if(d?.target_id!=a.id)continue;i.splice(r,1);const u=a.inputs[d.target_slot];u.link=null,u.widget&&s.trigger("node:slot-links:changed",{nodeId:a.id,slotType:j.INPUT,slotIndex:d.target_slot,connected:!1,linkId:d.id}),d.disconnect(s,"input"),s._version++,a.onConnectionsChange?.(j.INPUT,d.target_slot,!1,d,u),this.onConnectionsChange?.(j.OUTPUT,e,!1,d,n);break}}else{for(const a of i){const r=s._links.get(a);if(!r)continue;if(r.target_id===-20&&s instanceof De){const d=s.outputNode.slots[r.target_slot];d?d.linkIds.length=0:console.error("Missing subgraphOutput slot when disconnecting link")}const l=s.getNodeById(r.target_id);if(s._version++,l){const d=l.inputs[r.target_slot];d.link=null,d.widget&&s.trigger("node:slot-links:changed",{nodeId:l.id,slotType:j.INPUT,slotIndex:r.target_slot,connected:!1,linkId:r.id}),l.onConnectionsChange?.(j.INPUT,r.target_slot,!1,r,d)}r.disconnect(s,"input"),this.onConnectionsChange?.(j.OUTPUT,e,!1,r,n)}n.links=null}return this.setDirtyCanvas(!1,!0),!0}disconnectInput(e,t){if(typeof e=="string"){if(e=this.findInputSlot(e),e==-1)return _.debug&&console.error(`Connect: Error, no slot of name ${e}`),!1}else if(!this.inputs||e>=this.inputs.length)return _.debug&&console.error("Connect: Error, slot number not found"),!1;const n=this.inputs[e];if(!n)return console.error("disconnectInput: input not found",e,this.inputs),!1;const{graph:i}=this;if(!i)throw new N;if(n._floatingLinks?.size)for(const a of n._floatingLinks)i.removeFloatingLink(a);const s=this.inputs[e].link;if(s!=null){this.inputs[e].link=null,n.widget&&i.trigger("node:slot-links:changed",{nodeId:this.id,slotType:j.INPUT,slotIndex:e,connected:!1,linkId:s});const a=i._links.get(s);if(a){if(a.origin_id===-10&&"inputNode"in i)return i.inputNode._disconnectNodeInput(this,n,a),!0;const r=i.getNodeById(a.origin_id);if(!r)return console.error("disconnectInput: output not found",a.origin_slot),!1;const l=r.outputs[a.origin_slot];if(!l?.links?.length)return!1;let d=0;for(const u=l.links.length;d<u;d++)if(l.links[d]==s){l.links.splice(d,1);break}a.disconnect(i,t?"output":void 0),i&&i._version++,this.onConnectionsChange?.(j.INPUT,e,!1,a,n),r.onConnectionsChange?.(j.OUTPUT,d,!1,a,l)}}return this.setDirtyCanvas(!1,!0),!0}getConnectionPos(e,t,n){n||=[0,0];const{pos:[i,s],inputs:a,outputs:r}=this;if(this.flags.collapsed){const m=this._collapsed_width||_.NODE_COLLAPSED_WIDTH;return n[0]=e?i:i+m,n[1]=s-_.NODE_TITLE_HEIGHT*.5,n}if(e&&t==-1)return n[0]=i+_.NODE_TITLE_HEIGHT*.5,n[1]=s+_.NODE_TITLE_HEIGHT*.5,n;const l=a?.[t]?.pos,d=r?.[t]?.pos;if(e&&l)return n[0]=i+l[0],n[1]=s+l[1],n;if(!e&&d)return n[0]=i+d[0],n[1]=s+d[1],n;const u=_.NODE_SLOT_HEIGHT*.5,p=e?this.#c.indexOf(this.inputs[t]):this.#r.indexOf(this.outputs[t]);return n[0]=e?i+u:i+this.size[0]+1-u,n[1]=s+(p+.7)*_.NODE_SLOT_HEIGHT+(this.constructor.slot_start_y||0),n}get#c(){return this.inputs.filter(e=>!e.pos&&!(this.widgets?.length&&we(e)))}get#r(){return this.outputs.filter(e=>!e.pos)}#l(){return{nodeX:this.pos[0],nodeY:this.pos[1],nodeWidth:this.size[0],nodeHeight:this.size[1],collapsed:this.flags.collapsed??!1,collapsedWidth:this._collapsed_width,slotStartY:this.constructor.slot_start_y,inputs:this.inputs,outputs:this.outputs,widgets:this.widgets}}getInputPos(e){return ae(this,e,!0)}getInputSlotPos(e){return rn(this.#l(),e)}getOutputPos(e){return ae(this,e,!1)}getSlotPosition(e,t){return ae(this,e,t)}snapToGrid(e){return this.pinned?!1:xe(this.pos,e)}alignToGrid(){this.snapToGrid(_.CANVAS_GRID_SIZE)}trace(e){this.console||=[],this.console.push(e),this.console.length>Qe.MAX_CONSOLE&&this.console.shift()}setDirtyCanvas(e,t){this.graph?.canvasAction(n=>n.setDirty(e,t))}loadImage(e){const t=new Image;t.src=_.node_images_path+e,t.ready=!1;const n=h(()=>this.setDirtyCanvas(!0),"dirty");return t.addEventListener("load",function(){this.ready=!0,n()}),t}captureInput(e){if(Tn("[DEPRECATED] captureInput will be removed in a future version. Please use LGraphCanvas.pointer (CanvasPointer) instead."),!this.graph||!this.graph.list_of_graphcanvas)return;const t=this.graph.list_of_graphcanvas;for(const n of t)!e&&n.node_capturing_input!=this||(n.node_capturing_input=e?this:null)}get collapsed(){return!!this.flags.collapsed}get collapsible(){return!this.pinned&&this.constructor.collapsable!==!1}collapse(e){if(!(!this.collapsible&&!e)){if(!this.graph)throw new N;this.graph._version++,this.flags.collapsed=!this.flags.collapsed,this.setDirtyCanvas(!0,!0)}}toggleAdvanced(){if(this.widgets?.some(e=>e.advanced)){if(!this.graph)throw new N;this.graph._version++,this.showAdvanced=!this.showAdvanced,this.expandToFitContent(),this.setDirtyCanvas(!0,!0)}}get pinned(){return!!this.flags.pinned}pin(e){if(!this.graph)throw new N;this.graph._version++,this.flags.pinned=e??!this.flags.pinned,this.resizable=!this.pinned,this.pinned||(this.flags.pinned=void 0)}unpin(){this.pin(!1)}localToScreen(e,t,n){return[(e+this.pos[0])*n.scale+n.offset[0],(t+this.pos[1])*n.scale+n.offset[1]]}get width(){return this.collapsed?this._collapsed_width||_.NODE_COLLAPSED_WIDTH:this.size[0]}get height(){return _.NODE_TITLE_HEIGHT+this.bodyHeight}get bodyHeight(){return this.collapsed?0:this.size[1]}drawBadges(e,{gap:t=2}={}){const n=this.badges.map(a=>a instanceof io?a:a());let i=this.badgePosition===So.TopLeft?0:this.width-n.reduce((a,r)=>a+r.getWidth(e)+t,0);const s=-(_.NODE_TITLE_HEIGHT+t);for(const a of n)a.draw(e,i,s-a.height),i+=a.getWidth(e)+t}drawTitleBarBackground(e,{scale:t,title_height:n=_.NODE_TITLE_HEIGHT,low_quality:i=!1}){const s=this.renderingColor,a=this.renderingShape,r=this.renderingSize;if(this.onDrawTitleBar){this.onDrawTitleBar(e,n,r,t,s);return}this.title_mode!==se.TRANSPARENT_TITLE&&(this.collapsed&&(e.shadowColor=_.DEFAULT_SHADOW_COLOR),e.fillStyle=this.constructor.title_color||s,e.beginPath(),a==M.BOX||i?e.rect(0,-n,r[0],n):(a==M.ROUND||a==M.CARD)&&e.roundRect(0,-n,r[0],n,this.collapsed?[_.ROUND_RADIUS]:[_.ROUND_RADIUS,_.ROUND_RADIUS,0,0]),e.fill(),e.shadowColor="transparent")}drawTitleBox(e,{scale:t,low_quality:n=!1,title_height:i=_.NODE_TITLE_HEIGHT,box_size:s=10}){const a=this.renderingSize,r=this.renderingShape;if(this.onDrawTitleBox){this.onDrawTitleBox(e,i,a,t);return}[M.ROUND,M.CIRCLE,M.CARD].includes(r)?(n&&(e.fillStyle="black",e.beginPath(),e.arc(i*.5,i*-.5,s*.5+1,0,Math.PI*2),e.fill()),e.fillStyle=this.renderingBoxColor,n?e.fillRect(i*.5-s*.5,i*-.5-s*.5,s,s):(e.beginPath(),e.arc(i*.5,i*-.5,s*.5,0,Math.PI*2),e.fill())):(n&&(e.fillStyle="black",e.fillRect((i-s)*.5-1,(i+s)*-.5-1,s+2,s+2)),e.fillStyle=this.renderingBoxColor,e.fillRect((i-s)*.5,(i+s)*-.5,s,s))}drawTitleText(e,{scale:t,default_title_color:n,low_quality:i=!1,title_height:s=_.NODE_TITLE_HEIGHT}){const a=this.renderingSize,r=this.selected;if(this.onDrawTitleText){this.onDrawTitleText(e,s,a,t,this.titleFontStyle,r);return}if(i)return;e.font=this.titleFontStyle;const l=this.getTitle()??`❌ ${this.type}`,d=String(l)+(this.pinned?"📌":"");if(d){r?e.fillStyle=_.NODE_SELECTED_TITLE_COLOR:e.fillStyle=this.constructor.title_text_color||n;let u=a[0]-s*2;if(this.title_buttons?.length>0){let m=0;const g=e.font;for(const f of this.title_buttons)f.visible&&(m+=f.getWidth(e)+2);e.font=g,m>0&&(m-=20,u-=m)}let p=d;this.collapsed?p=d.substr(0,20):u>0&&(p=Rs(e,d,u)),e.textAlign="left",e.fillText(p,s,_.NODE_TITLE_TEXT_Y-s)}}connectInputToOutput(){const{inputs:e,outputs:t,graph:n}=this;if(!e||!t)return;if(!n)throw new N;const{_links:i}=n;let s=!1;for(const[r,l]of e.entries()){if(l.link==null)continue;const d=t[r];if(!d||!_.isValidConnection(l.type,d.type))continue;const u=i.get(l.link);if(!u)continue;const p=n.getNodeById(u?.origin_id);p&&a(d,p,u,n)}if(!(this.flags.keepAllLinksOnBypass??Qe.keepAllLinksOnBypass))return s;for(const r of e){if(r.link==null)continue;const l=i.get(r.link);if(!l)continue;const d=n.getNodeById(l?.origin_id);if(d){for(const u of t)if(_.isValidConnection(r.type,u.type)){a(u,d,l,n);break}}}return s;function a(r,l,d,u){const p=r.links?.map(m=>i.get(m)).filter(m=>!!m);if(p?.length)for(const m of p){const g=u.getNodeById(m.target_id);if(!g)continue;const f=l.connect(d.origin_slot,g,m.target_slot,d.parentId);s||=!!f}}}isWidgetVisible(e){return!(this.collapsed||e.hidden||e.advanced&&!this.showAdvanced)}updateComputedDisabled(){if(this.widgets)for(const e of this.widgets)e.computedDisabled=e.disabled||this.getSlotFromWidget(e)?.link!=null}drawWidgets(e,{lowQuality:t=!1,editorAlpha:n=1}){if(!this.widgets)return;const i=this.size[0],{widgets:s}=this,a=_.NODE_WIDGET_HEIGHT,r=!t;e.save(),e.globalAlpha=n,this.updateComputedDisabled();for(const l of s){if(!this.isWidgetVisible(l))continue;const{y:d}=l,u=l.advanced?_.WIDGET_ADVANCED_OUTLINE_COLOR:_.WIDGET_OUTLINE_COLOR;l.last_y=d,e.strokeStyle=u,e.fillStyle="#222",e.textAlign="left",l.computedDisabled&&(e.globalAlpha*=.5);const p=l.width||i;typeof l.draw=="function"?l.draw(e,this,p,d,a,t):Ct(l,this,!1)?.drawWidget(e,{width:p,showText:r}),e.globalAlpha=n}e.restore()}drawCollapsedSlots(e){for(const t of this.#e)if(t.link!=null){t.drawCollapsed(e);break}for(const t of this.#t)if(t.links?.length){t.drawCollapsed(e);break}}get slots(){return[...this.inputs,...this.outputs]}#u(e,t,n){const i=n?this.getInputPos(t):this.getOutputPos(t);e.boundingRect[0]=i[0]-_.NODE_SLOT_HEIGHT*.5,e.boundingRect[1]=i[1]-_.NODE_SLOT_HEIGHT*.5,e.boundingRect[2]=e.isWidgetInputSlot?B.margin:_.NODE_SLOT_HEIGHT,e.boundingRect[3]=_.NODE_SLOT_HEIGHT}#f(){const e=[];for(const[t,n]of this.#e.entries())this.widgets?.length&&we(n)||(this.#u(n,t,!0),e.push(n));for(const[t,n]of this.#t.entries())this.#u(n,t,!1),e.push(n);return e.length?et(e,0):null}#p(e){const t=es(e),n=this.mouseOver?.[t?"inputId":"outputId"]??-1;return n===-1?null:t?this.inputs[n]:this.outputs[n]}#m(e){return this.#p(e)===e}#_(e){return e?this.mouseOver?.overWidget===e:!1}getSlotFromWidget(e){if(e)return this.inputs.find(t=>we(t)&&t.widget.name===e.name)}getWidgetFromSlot(e){if(we(e))return this.widgets?.find(t=>t.name===e.widget.name)}drawSlots(e,{fromSlot:t,colorContext:n,editorAlpha:i,lowQuality:s}){for(const a of[...this.#e,...this.#t]){const r=t&&a.isValidTarget(t),l=this.#m(a),d=!t||r,u=d&&l;(l||r||!a.isWidgetInputSlot||this.#_(this.getWidgetFromSlot(a))||a.isConnected||a.alwaysVisible)&&(e.globalAlpha=d?i:.4*i,a.draw(e,{colorContext:n,lowQuality:s,highlight:u}))}}#v(e){if(!this.widgets||!this.widgets.length)return;const t=this.bodyHeight,n=this.widgets_start_y??(this.widgets_up?0:e)+2;let i=t-n,s=0;const a=[],r=this.widgets.filter(p=>!p.hidden);for(const p of r)if(p.computeSize){const m=p.computeSize()[1]+4;p.computedHeight=m,s+=m}else if(p.computeLayoutSize){const{minHeight:m,maxHeight:g}=p.computeLayoutSize(this);a.push({minHeight:m,prefHeight:g,w:p})}else{const m=_.NODE_WIDGET_HEIGHT+4;p.computedHeight=m,s+=m}i-=s,this.freeWidgetSpace=i;const l=a.map(p=>({minSize:p.minHeight,maxSize:p.prefHeight})),d=Ms(Math.max(0,i),l);for(const[p,m]of a.entries())m.w.computedHeight=d[p];let u=n;for(const p of r)p.y=u,u+=p.computedHeight??0;if(!this.graph)throw new N;u>t&&(this.setSize([this.size[0],u]),this.graph.setDirtyCanvas(!1,!0))}#b(){if(!this.widgets)return;const e=new Map;for(const[t,n]of this.inputs.entries())we(n)&&e.set(n.widget.name,{...n,index:t});if(e.size)if(_.vueNodesMode)for(const t of this.widgets){const n=e.get(t.name);n&&this.#u(this.#e[n.index],n.index,!0)}else for(const t of this.widgets){const n=e.get(t.name);if(!n)continue;const i=this.#e[n.index],s=_.NODE_SLOT_HEIGHT*.5;i.pos=[s,t.y+s],this.#u(i,n.index,!0)}}_setConcreteSlots(){this.#e=this.inputs.map(e=>U(Be,e,this)),this.#t=this.outputs.map(e=>U(mt,e,this))}arrange(){const e=this.#f(),t=e?e[1]+e[3]-this.pos[1]:0;this.#v(t),this.#b()}drawProgressBar(e){if(!this.progress)return;const t=e.fillStyle;e.fillStyle="green",e.fillRect(0,0,this.width*this.progress,6),e.fillStyle=t}},de=class ve{static{h(this,"LGraphGroup")}static minWidth=140;static minHeight=80;static resizeLength=10;static padding=4;static defaultColour="#335";id;color;title;font;font_size=_.DEFAULT_GROUP_FONT||24;_bounding=new X(10,10,ve.minWidth,ve.minHeight);_pos=this._bounding.pos;_size=this._bounding.size;_nodes=[];_children=new Set;graph;flags={};selected;constructor(e,t){this.id=t??-1,this.title=e||"Group";const{pale_blue:n}=ce.node_colors;this.color=n?n.groupcolor:"#AAA"}setColorOption(e){e==null?delete this.color:this.color=e.groupcolor}getColorOption(){return Object.values(ce.node_colors).find(e=>e.groupcolor===this.color)??null}get pos(){return this._pos}set pos(e){!e||e.length<2||(this._pos[0]=e[0],this._pos[1]=e[1])}get size(){return this._size}set size(e){!e||e.length<2||(this._size[0]=Math.max(ve.minWidth,e[0]),this._size[1]=Math.max(ve.minHeight,e[1]))}get boundingRect(){return this._bounding}getBounding(){return this._bounding}get nodes(){return this._nodes}get titleHeight(){return this.font_size*1.4}get children(){return this._children}get pinned(){return!!this.flags.pinned}pin(e){(e===void 0?!this.pinned:e)?this.flags.pinned=!0:delete this.flags.pinned}unpin(){this.pin(!1)}configure(e){this.id=e.id,this.title=e.title,this._bounding.set(e.bounding),this.color=e.color,this.flags=e.flags||this.flags,e.font_size&&(this.font_size=e.font_size)}serialize(){const e=this._bounding;return{id:this.id,title:this.title,bounding:[...e],color:this.color,font_size:this.font_size,flags:this.flags}}draw(e,t){const{padding:n,resizeLength:i,defaultColour:s}=ve,a=this.font_size||_.DEFAULT_GROUP_FONT_SIZE,[r,l]=this._pos,[d,u]=this._size,p=this.color||s;t.globalAlpha=.25*e.editor_alpha,t.fillStyle=p,t.strokeStyle=p,t.beginPath(),t.rect(r+.5,l+.5,d,a*1.4),t.fill(),t.fillStyle=p,t.strokeStyle=p,t.beginPath(),t.rect(r+.5,l+.5,d,u),t.fill(),t.globalAlpha=e.editor_alpha,t.stroke(),t.beginPath(),t.moveTo(r+d,l+u),t.lineTo(r+d-i,l+u),t.lineTo(r+d,l+u-i),t.fill(),t.font=`${a}px ${_.GROUP_FONT}`,t.textAlign="left",t.fillText(this.title+(this.pinned?"📌":""),r+n,l+a),_.highlight_selected_group&&this.selected&&gn(t,this._bounding,{title_height:this.titleHeight,padding:n})}resize(e,t){return this.pinned?!1:(this._size[0]=Math.max(ve.minWidth,e),this._size[1]=Math.max(ve.minHeight,t),!0)}move(e,t,n=!1){if(!this.pinned&&(this._pos[0]+=e,this._pos[1]+=t,n!==!0))for(const i of this._children)i.move(e,t)}snapToGrid(e){return this.pinned?!1:xe(this.pos,e)}recomputeInsideNodes(){if(!this.graph)throw new N;const{nodes:e,reroutes:t,groups:n}=this.graph,i=this._children;this._nodes.length=0,i.clear();for(const s of e)Gi(this._bounding,s.boundingRect)&&(this._nodes.push(s),i.add(s));for(const s of t.values())We(s.pos,this._bounding)&&i.add(s);for(const s of n)en(this._bounding,s._bounding)&&i.add(s);n.sort((s,a)=>s===this?i.has(a)?-1:0:a===this&&i.has(s)?1:0)}resizeTo(e,t=10){const n=et(e,t);n!==null&&(this.pos[0]=n[0],this.pos[1]=n[1]-this.titleHeight,this.size[0]=n[2],this.size[1]=n[3]+this.titleHeight)}addNodes(e,t=10){!this._nodes&&e.length===0||this.resizeTo([...this.children,...this._nodes,...e],t)}getMenuOptions(){return[{content:this.pinned?"Unpin":"Pin",callback:h(()=>{this.pinned?this.unpin():this.pin(),this.setDirtyCanvas(!1,!0)},"callback")},null,{content:"Title",callback:ce.onShowPropertyEditor},{content:"Color",has_submenu:!0,callback:ce.onMenuNodeColors},{content:"Font size",property:"font_size",type:"Number",callback:ce.onShowPropertyEditor},null,{content:"Remove",callback:ce.onMenuNodeRemove}]}isPointInTitlebar(e,t){const n=this.boundingRect;return G(e,t,n[0],n[1],n[2],this.titleHeight)}isInResize(e,t){const n=this.boundingRect,i=n[0]+n[2],s=n[1]+n[3];return e<i&&t<s&&e-i+(t-s)>-ve.resizeLength}isPointInside=q.prototype.isPointInside;setDirtyCanvas=q.prototype.setDirtyCanvas},Ao=class{static{h(this,"FloatingRenderLink")}node;fromSlot;fromPos;fromDirection;fromSlotIndex;outputNodeId=-1;outputNode;outputSlot;outputIndex=-1;outputPos;inputNodeId=-1;inputNode;inputSlot;inputIndex=-1;inputPos;constructor(o,e,t,n,i=O.CENTER){this.network=o,this.link=e,this.toType=t,this.fromReroute=n,this.dragDirection=i;const{origin_id:s,target_id:a,origin_slot:r,target_slot:l}=e;if(s!==-1){const d=o.getNodeById(s)??void 0;if(!d)throw new Error(`Creating DraggingRenderLink for link [${e.id}] failed: Output node [${s}] not found.`);const u=d?.outputs.at(r);if(!u)throw new Error(`Creating DraggingRenderLink for link [${e.id}] failed: Output slot [${r}] not found.`);this.outputNodeId=s,this.outputNode=d,this.outputSlot=u,this.outputIndex=r,this.outputPos=d.getOutputPos(r),this.node=d,this.fromSlot=u,this.fromPos=n?.pos??this.outputPos,this.fromDirection=O.LEFT,this.dragDirection=O.RIGHT,this.fromSlotIndex=r}else{const d=o.getNodeById(a)??void 0;if(!d)throw new Error(`Creating DraggingRenderLink for link [${e.id}] failed: Input node [${a}] not found.`);const u=d?.inputs.at(l);if(!u)throw new Error(`Creating DraggingRenderLink for link [${e.id}] failed: Input slot [${l}] not found.`);this.inputNodeId=a,this.inputNode=d,this.inputSlot=u,this.inputIndex=l,this.inputPos=d.getInputPos(l),this.node=d,this.fromSlot=u,this.fromDirection=O.RIGHT,this.fromSlotIndex=l}this.fromPos=n.pos}canConnectToInput(){return this.toType==="input"}canConnectToOutput(){return this.toType==="output"}canConnectToReroute(o){if(this.toType==="input"){if(o.origin_id===this.inputNode?.id)return!1}else if(o.origin_id===this.outputNode?.id)return!1;return!0}canConnectToSubgraphInput(o){return this.toType==="output"&&o.isValidTarget(this.fromSlot)}connectToInput(o,e,t){const n=this.link;n.target_id=o.id,n.target_slot=o.inputs.indexOf(e),o.disconnectInput(o.inputs.indexOf(e)),this.fromSlot._floatingLinks?.delete(n),e._floatingLinks??=new Set,e._floatingLinks.add(n)}connectToOutput(o,e,t){const n=this.link;n.origin_id=o.id,n.origin_slot=o.outputs.indexOf(e),this.fromSlot._floatingLinks?.delete(n),e._floatingLinks??=new Set,e._floatingLinks.add(n)}connectToSubgraphInput(o,e){const t=this.link;t.origin_id=-10,t.origin_slot=o.parent.slots.indexOf(o),this.fromSlot._floatingLinks?.delete(t),o._floatingLinks??=new Set,o._floatingLinks.add(t)}connectToSubgraphOutput(o,e){const t=this.link;t.origin_id=-20,t.origin_slot=o.parent.slots.indexOf(o),this.fromSlot._floatingLinks?.delete(t),o._floatingLinks??=new Set,o._floatingLinks.add(t)}connectToRerouteInput(o,{node:e,input:t},n){const i=this.link;i.target_id=e.id,i.target_slot=e.inputs.indexOf(t),this.fromSlot._floatingLinks?.delete(i),t._floatingLinks??=new Set,t._floatingLinks.add(i),n.dispatch("input-moved",this)}connectToRerouteOutput(o,e,t,n){const i=this.link;i.origin_id=e.id,i.origin_slot=e.outputs.indexOf(t),this.fromSlot._floatingLinks?.delete(i),t._floatingLinks??=new Set,t._floatingLinks.add(i),n.dispatch("output-moved",this)}},Tt=class{static{h(this,"MovingLinkBase")}outputNodeId;outputNode;outputSlot;outputIndex;outputPos;inputNodeId;inputNode;inputSlot;inputIndex;inputPos;constructor(o,e,t,n,i=O.CENTER){this.network=o,this.link=e,this.toType=t,this.fromReroute=n,this.dragDirection=i;const{origin_id:s,target_id:a,origin_slot:r,target_slot:l}=e,d=o.getNodeById(s)??void 0;if(!d)throw new Error(`Creating MovingRenderLink for link [${e.id}] failed: Output node [${s}] not found.`);const u=d.outputs.at(r);if(!u)throw new Error(`Creating MovingRenderLink for link [${e.id}] failed: Output slot [${r}] not found.`);this.outputNodeId=s,this.outputNode=d,this.outputSlot=u,this.outputIndex=r,this.outputPos=d.getOutputPos(r);const p=o.getNodeById(a)??void 0;if(!p)throw new Error(`Creating DraggingRenderLink for link [${e.id}] failed: Input node [${a}] not found.`);const m=p.inputs.at(l);if(!m)throw new Error(`Creating DraggingRenderLink for link [${e.id}] failed: Input slot [${l}] not found.`);this.inputNodeId=a,this.inputNode=p,this.inputSlot=m,this.inputIndex=l,this.inputPos=p.getInputPos(l)}},Ow=class extends Tt{static{h(this,"MovingInputLink")}toType="input";node;fromSlot;fromPos;fromDirection;fromSlotIndex;constructor(o,e,t,n=O.CENTER){super(o,e,"input",t,n),this.node=this.outputNode,this.fromSlot=this.outputSlot,this.fromPos=t?.pos??this.outputPos,this.fromDirection=O.NONE,this.fromSlotIndex=this.outputIndex}canConnectToInput(o,e){return this.node.canConnectTo(o,e,this.outputSlot)}canConnectToOutput(){return!1}canConnectToReroute(o){return o.origin_id!==this.inputNode.id}connectToInput(o,e,t){if(e===this.inputSlot)return;this.inputNode.disconnectInput(this.inputIndex,!0);const n=this.outputNode.connectSlots(this.outputSlot,o,e,this.fromReroute?.id);return n&&t.dispatch("input-moved",this),n}connectToOutput(){throw new Error("MovingInputLink cannot connect to an output.")}connectToSubgraphInput(){throw new Error("MovingInputLink cannot connect to a subgraph input.")}connectToSubgraphOutput(o,e){const t=o.connect(this.fromSlot,this.node,this.fromReroute?.id);e?.dispatch("link-created",t)}connectToRerouteInput(o,{node:e,input:t,link:n},i,s){const{outputNode:a,outputSlot:r,fromReroute:l}=this;for(const d of s){if(d.id===this.link.parentId)break;d.totalLinks===1&&d.remove()}o.parentId=l?.id,a.connectSlots(r,e,t,n.parentId)&&i.dispatch("input-moved",this)}connectToRerouteOutput(){throw new Error("MovingInputLink cannot connect to an output.")}disconnect(){return this.inputNode.disconnectInput(this.inputIndex,!0)}},Do=class extends Tt{static{h(this,"MovingOutputLink")}toType="output";node;fromSlot;fromPos;fromDirection;fromSlotIndex;constructor(o,e,t,n=O.CENTER){super(o,e,"output",t,n),this.node=this.inputNode,this.fromSlot=this.inputSlot,this.fromPos=t?.pos??this.inputPos,this.fromDirection=O.LEFT,this.fromSlotIndex=this.inputIndex}canConnectToInput(){return!1}canConnectToOutput(o,e){return o.canConnectTo(this.node,this.inputSlot,e)}canConnectToReroute(o){return o.origin_id!==this.outputNode.id}canConnectToSubgraphInput(o){return o.isValidTarget(this.fromSlot)}connectToInput(){throw new Error("MovingOutputLink cannot connect to an input.")}connectToOutput(o,e,t){if(e===this.outputSlot)return;const n=o.connectSlots(e,this.inputNode,this.inputSlot,this.link.parentId);return n&&t.dispatch("output-moved",this),n}connectToSubgraphInput(o,e){const t=o.connect(this.fromSlot,this.node,this.fromReroute?.id);e?.dispatch("link-created",t)}connectToSubgraphOutput(){throw new Error("MovingOutputLink cannot connect to a subgraph output.")}connectToRerouteInput(){throw new Error("MovingOutputLink cannot connect to an input.")}connectToRerouteOutput(o,e,t,n){const{inputNode:i,inputSlot:s,fromReroute:a}=this,r=o?.floating?.slotType==="output";a?a.parentId=o.id:this.link.parentId=o.id,e.connectSlots(t,i,s,this.link.parentId),r&&o.removeAllFloatingLinks(),n.dispatch("output-moved",this)}disconnect(){return this.outputNode.disconnectOutput(this.outputIndex,this.inputNode)}},dt=class{static{h(this,"ToInputFromIoNodeLink")}toType="input";fromSlotIndex;fromPos;fromDirection=O.RIGHT;existingLink;constructor(o,e,t,n,i=O.CENTER,s){this.network=o,this.node=e,this.fromSlot=t,this.fromReroute=n,this.dragDirection=i;const a=e.slots.indexOf(t);if(a===-1&&t!==e.emptySlot)throw new Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);this.fromSlotIndex=a,this.fromPos=n?n.pos:t.pos,this.existingLink=s}canConnectToInput(o,e){return this.node.canConnectTo(o,e,this.fromSlot)}canConnectToOutput(){return!1}connectToInput(o,e,t){const{fromSlot:n,fromReroute:i,existingLink:s}=this,a=n.connect(e,o,i?.id);if(s){const{input:r,inputNode:l}=s.resolve(this.network);l&&r&&this.node._disconnectNodeInput(l,r,s),t.dispatch("input-moved",this)}else t.dispatch("link-created",a)}connectToSubgraphOutput(){throw new Error("Not implemented")}connectToRerouteInput(o,{node:e,input:t,link:n},i,s){const{fromSlot:a,fromReroute:r}=this,l=r?.floating?.slotType==="output";o.parentId=r?.id;const d=a.connect(t,e,n.parentId);l&&r.removeAllFloatingLinks();for(const u of s){if(u.id===r?.id)break;if(u.removeLink(n),u.totalLinks===0)if(n.isFloating)u.remove();else{const p=n.toFloating("output",u.id);this.network.addFloatingLink(p),u.floating={slotType:"output"}}}this.existingLink?i.dispatch("input-moved",this):i.dispatch("link-created",d)}connectToOutput(){throw new Error("ToInputRenderLink cannot connect to an output.")}connectToSubgraphInput(){throw new Error("ToInputRenderLink cannot connect to a subgraph input.")}connectToRerouteOutput(){throw new Error("ToInputRenderLink cannot connect to an output.")}disconnect(){if(!this.existingLink)return!1;const{input:o,inputNode:e}=this.existingLink.resolve(this.network);return!e||!o?!1:(this.node._disconnectNodeInput(e,o,this.existingLink),!0)}},ze=class{static{h(this,"ToInputRenderLink")}toType="input";fromPos;fromSlotIndex;fromDirection=O.RIGHT;constructor(o,e,t,n,i=O.CENTER){this.network=o,this.node=e,this.fromSlot=t,this.fromReroute=n,this.dragDirection=i;const s=e.outputs.indexOf(t);if(s===-1)throw new Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);this.fromSlotIndex=s,this.fromPos=n?n.pos:this.node.getOutputPos(s)}canConnectToInput(o,e){return this.node.canConnectTo(o,e,this.fromSlot)}canConnectToOutput(){return!1}connectToInput(o,e,t){const{node:n,fromSlot:i,fromReroute:s}=this;if(o===n)return;const a=n.connectSlots(i,o,e,s?.id);t.dispatch("link-created",a)}connectToSubgraphOutput(o,e){const t=o.connect(this.fromSlot,this.node,this.fromReroute?.id);e.dispatch("link-created",t)}connectToRerouteInput(o,{node:e,input:t,link:n},i,s){const{node:a,fromSlot:r,fromReroute:l}=this,d=l?.floating?.slotType==="output";o.parentId=l?.id;const u=a.connectSlots(r,e,t,n.parentId);d&&l.removeAllFloatingLinks();for(const p of s){if(p.id===l?.id)break;if(p.removeLink(n),p.totalLinks===0)if(n.isFloating)p.remove();else{const m=n.toFloating("output",p.id);this.network.addFloatingLink(m),p.floating={slotType:"output"}}}i.dispatch("link-created",u)}connectToOutput(){throw new Error("ToInputRenderLink cannot connect to an output.")}connectToSubgraphInput(){throw new Error("ToInputRenderLink cannot connect to a subgraph input.")}connectToRerouteOutput(){throw new Error("ToInputRenderLink cannot connect to an output.")}},Vt=class{static{h(this,"ToOutputFromIoNodeLink")}toType="output";fromPos;fromSlotIndex;fromDirection=O.LEFT;constructor(o,e,t,n,i=O.CENTER){this.network=o,this.node=e,this.fromSlot=t,this.fromReroute=n,this.dragDirection=i;const s=e.slots.indexOf(t);if(s===-1&&t!==e.emptySlot)throw new Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);this.fromSlotIndex=s,this.fromPos=n?n.pos:t.pos}canConnectToInput(){return!1}canConnectToOutput(o,e){return this.node.canConnectTo(o,this.fromSlot,e)}canConnectToReroute(o){return o.origin_id!==this.node.id}connectToOutput(o,e,t){const{fromSlot:n,fromReroute:i}=this,s=n.connect(e,o,i?.id);t.dispatch("link-created",s)}connectToSubgraphInput(){throw new Error("Not implemented")}connectToRerouteOutput(o,e,t,n){const{fromSlot:i}=this,s=i.connect(t,e,o?.id);n.dispatch("link-created",s)}connectToInput(){throw new Error("ToOutputRenderLink cannot connect to an input.")}connectToSubgraphOutput(){throw new Error("ToOutputRenderLink cannot connect to a subgraph output.")}connectToRerouteInput(){throw new Error("ToOutputRenderLink cannot connect to an input.")}},xn=class{static{h(this,"ToOutputRenderLink")}toType="output";fromPos;fromSlotIndex;fromDirection=O.LEFT;constructor(o,e,t,n,i=O.CENTER){this.network=o,this.node=e,this.fromSlot=t,this.fromReroute=n,this.dragDirection=i;const s=e.inputs.indexOf(t);if(s===-1)throw new Error(`Creating render link for node [${this.node.id}] failed: Slot index not found.`);this.fromSlotIndex=s,this.fromPos=n?n.pos:this.node.getInputPos(s)}canConnectToInput(){return!1}canConnectToOutput(o,e){return this.node.canConnectTo(o,this.fromSlot,e)}canConnectToReroute(o){return o.origin_id!==this.node.id}canConnectToSubgraphInput(o){return o.isValidTarget(this.fromSlot)}connectToOutput(o,e,t){const{node:n,fromSlot:i,fromReroute:s}=this;if(!n)return;const a=o.connectSlots(e,n,i,s?.id);t.dispatch("link-created",a)}connectToSubgraphInput(o,e){const t=o.connect(this.fromSlot,this.node,this.fromReroute?.id);e?.dispatch("link-created",t)}connectToRerouteOutput(o,e,t,n){const{node:i,fromSlot:s}=this,a=e.connectSlots(t,i,s,o?.id);n.dispatch("link-created",a)}connectToInput(){throw new Error("ToOutputRenderLink cannot connect to an input.")}connectToSubgraphOutput(){throw new Error("ToOutputRenderLink cannot connect to a subgraph output.")}connectToRerouteInput(){throw new Error("ToOutputRenderLink cannot connect to an input.")}},Pw=class extends xn{static{h(this,"ToOutputFromRerouteLink")}constructor(o,e,t,n,i){super(o,e,t,n),this.fromReroute=n,this.linkConnector=i}canConnectToReroute(){return!1}connectToOutput(o,e){const t=new ze(this.network,o,e);this.linkConnector._connectOutputToReroute(this.fromReroute,t)}},Mw=class{static{h(this,"LinkConnector")}state={connectingTo:void 0,multi:!1,draggingExistingLinks:!1,snapLinksPos:void 0};events=new Et;renderLinks=[];inputLinks=[];outputLinks=[];floatingLinks=[];hiddenReroutes=new Set;overWidget;overWidgetType;overReroute;#e;constructor(o){this.#e=o}get isConnecting(){return this.state.connectingTo!==void 0}get draggingExistingLinks(){return this.state.draggingExistingLinks}moveInputLink(o,e){if(this.isConnecting)throw new Error("Already dragging links.");const{state:t,inputLinks:n,renderLinks:i}=this,s=e.link;if(s==null){const a=e._floatingLinks?.values().next().value;if(a?.parentId==null)return;try{const r=o.reroutes.get(a.parentId);if(!r)throw new Error(`Invalid reroute id: [${a.parentId}] for floating link id: [${a.id}].`);const l=new Ao(o,a,"input",r);if(this.events.dispatch("before-move-input",l)===!1)return;i.push(l)}catch(r){console.warn(`Could not create render link for link id: [${a.id}].`,a,r)}a._dragging=!0,this.floatingLinks.push(a)}else{const a=o.links.get(s);if(!a)return;if(a.origin_id===-10){const r=o.inputNode?.slots[a.origin_slot];if(!r){console.warn(`Could not find subgraph input for slot [${a.origin_slot}]`);return}try{const l=o.getReroute(a.parentId),d=new dt(o,o.inputNode,r,l,O.CENTER,a);i.push(d),this.listenUntilReset("input-moved",()=>{a.disconnect(o,"input")})}catch(l){console.warn(`Could not create render link for subgraph input link id: [${a.id}].`,a,l);return}a._dragging=!0,n.push(a)}else{try{const r=new Ow(o,a,o.getReroute(a.parentId));if(this.events.dispatch("before-move-input",r)===!1)return;i.push(r),this.listenUntilReset("input-moved",l=>{"link"in l.detail&&l.detail.link&&l.detail.link.disconnect(o,"output")})}catch(r){console.warn(`Could not create render link for link id: [${a.id}].`,a,r);return}a._dragging=!0,n.push(a)}}t.connectingTo="input",t.draggingExistingLinks=!0,this.#n(!1)}moveOutputLink(o,e){if(this.isConnecting)throw new Error("Already dragging links.");const{state:t,renderLinks:n}=this;if(e._floatingLinks?.size)for(const i of e._floatingLinks.values())try{const s=z.getFirstReroute(o,i);if(!s)throw new Error(`Invalid reroute id: [${i.parentId}] for floating link id: [${i.id}].`);const a=new Ao(o,i,"output",s);if(this.events.dispatch("before-move-output",a)===!1)continue;n.push(a),this.floatingLinks.push(i)}catch(s){console.warn(`Could not create render link for link id: [${i.id}].`,i,s)}if(e.links?.length)for(const i of e.links){const s=o.links.get(i);if(!s)continue;const a=z.getFirstReroute(o,s);a?(a._dragging=!0,this.hiddenReroutes.add(a)):s._dragging=!0,this.outputLinks.push(s);try{if(s.target_id===-20){if(!(o instanceof De)){console.warn("Subgraph output link found in non-subgraph network.");continue}const l=o.outputs.at(s.target_slot);if(!l)throw new Error("No subgraph output found for link.");const d=new Vt(o,o.outputNode,l);d.fromDirection=O.NONE,n.push(d);continue}const r=new Do(o,s,a,O.RIGHT);if(this.events.dispatch("before-move-output",r)===!1)continue;n.push(r)}catch(r){console.warn(`Could not create render link for link id: [${s.id}].`,s,r);continue}}n.length!==0&&(t.draggingExistingLinks=!0,t.multi=!0,t.connectingTo="output",this.#n(!0))}dragNewFromOutput(o,e,t,n){if(this.isConnecting)throw new Error("Already dragging links.");const{state:i}=this,s=new ze(o,e,t,n);this.renderLinks.push(s),i.connectingTo="input",this.#n(!1)}dragNewFromInput(o,e,t,n){if(this.isConnecting)throw new Error("Already dragging links.");const{state:i}=this,s=new xn(o,e,t,n);this.renderLinks.push(s),i.connectingTo="output",this.#n(!0)}dragNewFromSubgraphInput(o,e,t,n){if(this.isConnecting)throw new Error("Already dragging links.");const i=new dt(o,e,t,n);this.renderLinks.push(i),this.state.connectingTo="input",this.#n(!1)}dragNewFromSubgraphOutput(o,e,t,n){if(this.isConnecting)throw new Error("Already dragging links.");const i=new Vt(o,e,t,n);this.renderLinks.push(i),this.state.connectingTo="output",this.#n(!0)}dragFromReroute(o,e){if(this.isConnecting)throw new Error("Already dragging links.");const t=e.firstLink??e.firstFloatingLink;if(!t){console.warn("No link found for reroute.");return}if(t.origin_id===-10){if(!(o instanceof De)){console.warn("Subgraph input link found in non-subgraph network.");return}const a=o.inputs.at(t.origin_slot);if(!a)throw new Error("No subgraph input found for link.");const r=new dt(o,o.inputNode,a,e);r.fromDirection=O.NONE,this.renderLinks.push(r),this.state.connectingTo="input",this.#n(!1);return}const n=o.getNodeById(t.origin_id);if(!n){console.warn("No output node found for link.",t);return}const i=n.outputs.at(t.origin_slot);if(!i){console.warn("No output slot found for link.",t);return}const s=new ze(o,n,i,e);s.fromDirection=O.NONE,this.renderLinks.push(s),this.state.connectingTo="input",this.#n(!1)}dragFromRerouteToOutput(o,e){if(this.isConnecting)throw new Error("Already dragging links.");const t=e.firstLink??e.firstFloatingLink;if(!t){console.warn("No link found for reroute.");return}if(t.target_id===-20){if(!(o instanceof De)){console.warn("Subgraph output link found in non-subgraph network.");return}const a=o.outputs.at(t.target_slot);if(!a)throw new Error("No subgraph output found for link.");const r=new Vt(o,o.outputNode,a,e);r.fromDirection=O.NONE,this.renderLinks.push(r),this.state.connectingTo="output",this.#n(!1);return}const n=o.getNodeById(t.target_id);if(!n){console.warn("No input node found for link.",t);return}const i=n.inputs.at(t.target_slot);if(!i){console.warn("No input slot found for link.",t);return}const s=new Pw(o,n,i,e,this);s.fromDirection=O.LEFT,this.renderLinks.push(s),this.state.connectingTo="output",this.#n(!0)}dragFromLinkSegment(o,e){if(this.isConnecting)throw new Error("Already dragging links.");const{state:t}=this;if(e.origin_id==null||e.origin_slot==null)return;const n=o.getNodeById(e.origin_id);if(!n)return;const i=n.outputs.at(e.origin_slot);if(!i)return;const s=new ze(o,n,i,o.getReroute(e.parentId));s.fromDirection=O.NONE,this.renderLinks.push(s),t.connectingTo="input",this.#n(!1)}dropLinks(o,e){if(!(!this.isConnecting&&this.events.dispatch("before-drop-links",{renderLinks:this.renderLinks,event:e})===!1))try{const{canvasX:t,canvasY:n}=e,i=o.getIoNodeOnPos?.(t,n);if(i){this.dropOnIoNode(i,e);return}const s=o.getNodeOnPos(t,n)??void 0;if(s)this.dropOnNode(s,e);else{const a=o.getRerouteOnPos(t,n);a&&this.isRerouteValidDrop(a)?this.dropOnReroute(a,e):this.dropOnNothing(e)}}finally{this.events.dispatch("after-drop-links",{renderLinks:this.renderLinks,event:e})}}dropOnIoNode(o,e){const{renderLinks:t,state:n}=this,{connectingTo:i}=n,{canvasX:s,canvasY:a}=e;if(i==="input"&&o instanceof xt){const r=o.getSlotInPosition(s,a);if(!r){this.dropOnNothing(e);return}let l=r;for(const d of t)if(d.connectToSubgraphOutput(l,this.events),r instanceof kn&&o.slots.length>0){const u=o.slots[o.slots.length-1],p=t[t.indexOf(d)+1];p&&d.fromSlot.type===p.fromSlot.type?l=u:l=r}}else if(i==="output"&&o instanceof Nt){const r=o.getSlotInPosition(s,a);if(!r){this.dropOnNothing(e);return}let l=r;for(const d of t){if("canConnectToSubgraphInput"in d&&!d.canConnectToSubgraphInput(l)){console.warn("Invalid connection type",d.fromSlot.type,"->",l.type);continue}if(d.connectToSubgraphInput(l,this.events),r instanceof bn&&o.slots.length>0){const u=o.slots[o.slots.length-1],p=t[t.indexOf(d)+1];p&&d.fromSlot.type===p.fromSlot.type?l=u:l=r}}}else console.error("Invalid connectingTo state &/ ioNode",i,o)}dropOnNode(o,e){const{renderLinks:t,state:n}=this,{connectingTo:i}=n,{canvasX:s,canvasY:a}=e;if(!t.every(r=>r.node===o)){if(i==="output"){const r=o.getOutputOnPos([s,a]);r?this.#o(o,r):this.connectToNode(o,e)}else if(i==="input"){const r=o.getInputOnPos([s,a])??o.getSlotFromWidget(this.overWidget);r?this.#t(o,r):this.connectToNode(o,e)}}}dropOnReroute(o,e){if(this.events.dispatch("dropped-on-reroute",{reroute:o,event:e})!==!1){if(this.state.connectingTo==="input"){if(this.renderLinks.length!==1)throw new Error(`Attempted to connect ${this.renderLinks.length} input links to a reroute.`);const t=this.renderLinks[0];this._connectOutputToReroute(o,t);return}for(const t of this.renderLinks){if(t.toType!=="output")continue;const n=o.findSourceOutput();if(!n)continue;const{node:i,output:s}=n;t.canConnectToOutput(i,s)&&t.connectToRerouteOutput(o,i,s,this.events)}}}_connectOutputToReroute(o,e){const t=o.findTargetInputs();if(!t?.length)return;const n=o.getReroutes();if(n===null)throw new Error("Reroute loop detected.");const i=n.slice(0,-1).reverse();if(e instanceof ze){const{node:a,fromSlot:r,fromSlotIndex:l,fromReroute:d}=e;if(o.setFloatingLinkOrigin(a,r,l),d!=null)for(const u of i){if(u.id===d.id)break;for(const p of o.floatingLinkIds)u.floatingLinkIds.delete(p)}}const s=t.filter(a=>e.toType==="input"&&Oo(e,a.node,a.input,o));for(const a of s)e.connectToRerouteInput(o,a,this.events,i)}dropOnNothing(o){this.events.dispatch("dropped-on-canvas",o)!==!1&&this.disconnectLinks()}disconnectLinks(){for(const o of this.renderLinks)(o instanceof Tt||o instanceof dt)&&o.disconnect()}connectToNode(o,e){const{state:{connectingTo:t}}=this;if(this.events.dispatch("dropped-on-node",{node:o,event:e})===!1)return;const n=this.renderLinks[0];if(n){if(t==="output"){const i=o.findOutputByType(n.fromSlot.type)?.slot;if(i===void 0){console.warn(`Could not find slot for link type: [${n.fromSlot.type}].`);return}this.#o(o,i)}else if(t==="input"){const i=o.findInputByType(n.fromSlot.type)?.slot;if(i===void 0){console.warn(`Could not find slot for link type: [${n.fromSlot.type}].`);return}this.#t(o,i)}}}#t(o,e){for(const t of this.renderLinks)t.canConnectToInput(o,e)&&t.connectToInput(o,e,this.events)}#o(o,e){for(const t of this.renderLinks){if(!t.canConnectToOutput(o,e)){t instanceof Do&&t.link.parentId!==void 0&&t.outputNode.connectSlots(t.outputSlot,t.inputNode,t.inputSlot,void 0);continue}t.connectToOutput(o,e,this.events)}}isInputValidDrop(o,e){return this.renderLinks.some(t=>t.canConnectToInput(o,e))}isNodeValidDrop(o){return this.state.connectingTo==="output"?o.outputs.some(e=>this.renderLinks.some(t=>t.canConnectToOutput(o,e))):o.inputs.some(e=>this.renderLinks.some(t=>t.canConnectToInput(o,e)))}isSubgraphInputValidDrop(o){return this.renderLinks.some(e=>"canConnectToSubgraphInput"in e&&e.canConnectToSubgraphInput(o))}isRerouteValidDrop(o){if(this.state.connectingTo==="input"){const e=o.findTargetInputs();if(!e?.length)return!1;for(const{node:t,input:n}of e)for(const i of this.renderLinks)if(i.toType==="input"&&Oo(i,t,n,o))return!0}else{const e=o.findSourceOutput();if(!e)return!1;const{node:t,output:n}=e;for(const i of this.renderLinks)if(i.toType==="output"&&i.canConnectToReroute(o)&&i.canConnectToOutput(t,n))return!0}return!1}#n(o){const e=this.renderLinks.map(t=>{const n=o?t.fromSlot:null,i=o?null:t.fromSlot,s=t instanceof Tt?t.link?.parentId:t.fromReroute?.id;return{node:t.node,slot:t.fromSlotIndex,input:n,output:i,pos:t.fromPos,afterRerouteId:s}});this.#e(e)}export(o){return{renderLinks:[...this.renderLinks],inputLinks:[...this.inputLinks],outputLinks:[...this.outputLinks],floatingLinks:[...this.floatingLinks],state:{...this.state},network:o}}listenUntilReset(o,e,t){this.events.addEventListener(o,e,t),this.events.addEventListener("reset",()=>this.events.removeEventListener(o,e),{once:!0})}reset(o=!1){if(this.events.dispatch("reset",o)===!1)return;const{state:e,outputLinks:t,inputLinks:n,hiddenReroutes:i,renderLinks:s,floatingLinks:a}=this;if(!(!o&&e.connectingTo===void 0)){e.connectingTo=void 0;for(const r of t)delete r._dragging;for(const r of n)delete r._dragging;for(const r of a)delete r._dragging;for(const r of i)delete r._dragging;s.length=0,n.length=0,t.length=0,a.length=0,i.clear(),e.multi=!1,e.draggingExistingLinks=!1,e.snapLinksPos=void 0}}};function Oo(o,e,t,n){const{fromReroute:i}=o;if(!o.canConnectToInput(e,t)||i?.id===n.id||i?.getReroutes()?.includes(n))return!1;if(o instanceof ze){if(n.parentId==null){if(n.firstLink?.hasOrigin(o.node.id,o.fromSlotIndex))return!1}else if(o.fromReroute?.id===n.parentId)return!1}return!0}h(Oo,"canConnectInputLinkToReroute");var Qt=class extends Error{static{h(this,"RecursionError")}constructor(o){super(o),this.name="RecursionError"}},ut=class extends Error{static{h(this,"InvalidLinkError")}constructor(o="Attempted to access a link that was invalid.",e){super(o,{cause:e}),this.name="InvalidLinkError"}},Ut=class extends Error{static{h(this,"SlotIndexError")}constructor(o="Attempted to access a slot that was out of bounds.",e){super(o,{cause:e}),this.name="SlotIndexError"}},Po=class{static{h(this,"ExecutableNodeDTO")}graph;inputs;#e;get id(){return this.#e}get type(){return this.node.type}get title(){return this.node.title}get mode(){return this.node.mode}get comfyClass(){return this.node.comfyClass}get isVirtualNode(){return this.node.isVirtualNode}get widgets(){return this.node.widgets}get subgraphId(){return this.subgraphNode?.subgraph.id}constructor(o,e,t,n){if(this.node=o,this.subgraphNodePath=e,this.nodesByExecutionId=t,this.subgraphNode=n,!o.graph)throw new N;this.#e=[...this.subgraphNodePath,this.node.id].join(":"),this.graph=o.graph,this.inputs=this.node.inputs.map(i=>({linkId:i.link,name:i.name,type:i.type})),this.node.applyToGraph&&(this.applyToGraph=(...i)=>this.node.applyToGraph?.(...i))}getInnerNodes(){return this.node.isSubgraphNode()?this.node.getInnerNodes(this.nodesByExecutionId,this.subgraphNodePath):[this]}resolveInput(o,e=new Set,t){const n=`${this.subgraphNode?.subgraph.id}:${this.node.id}[I]${o}`;if(e.has(n))throw new Qt(`Circular reference detected while resolving input ${o} of node ${`${this.node.id}${this.node.title?` (${this.node.title})`:""}`}${this.subgraphNodePath.length>0?` at path ${this.subgraphNodePath.join(":")}`:""}. This creates an infinite loop in link resolution. UniqueID: [${n}]`);e.add(n);const i=this.inputs.at(o);if(!i)throw new Ut(`No input found for flattened id [${this.id}] slot [${o}]`);if(i.linkId==null)return;const s=this.graph.getLink(i.linkId);if(!s)throw new ut(`No link found in parent graph for id [${this.id}] slot [${o}] ${i.name}`);const{subgraphNode:a}=this;if(a&&s.originIsIoNode){const u=a.inputs.at(s.origin_slot);if(!u)throw new Ut(`No input found for slot [${s.origin_slot}] ${i.name}`);const p=u.link;if(p==null){const y=a.getWidgetFromSlot(u);return y?{node:this,origin_id:this.id,origin_slot:-1,widgetInfo:{value:y.value}}:void 0}const m=a.graph.getLink(p);if(!m)throw new ut(`No outer link found for slot [${s.origin_slot}] ${i.name}`);const g=this.subgraphNodePath.join(":"),f=this.nodesByExecutionId.get(g);if(!f)throw new Error(`No subgraph node DTO found for id [${g}]`);return f.resolveInput(m.target_slot,e)}const r=this.graph.getNodeById(s.origin_id);if(!r)throw new ut(`No input node found for id [${this.id}] slot [${o}] ${i.name}`);const l=[...this.subgraphNodePath,r.id].join(":"),d=this.nodesByExecutionId.get(l);if(!d)throw new Error(`No output node DTO found for id [${l}]`);return d.resolveOutput(s.origin_slot,t??i.type,e)}resolveOutput(o,e,t){const n=`${this.subgraphNode?.subgraph.id}:${this.node.id}[O]${o}`;if(t.has(n))throw new Qt(`Circular reference detected while resolving output ${o} of node ${`${this.node.id}${this.node.title?` (${this.node.title})`:""}`}${this.subgraphNodePath.length>0?` at path ${this.subgraphNodePath.join(":")}`:""}. This creates an infinite loop in link resolution. UniqueID: [${n}]`);if(t.add(n),this.mode===H.BYPASS){const s=this.#t(o,e);if(s===-1){console.warn(`[ExecutableNodeDTO.resolveOutput] No input types match type [${e}] for id [${this.id}] slot [${o}]`,this);return}return this.resolveInput(s,t)}const{node:i}=this;if(i.isSubgraphNode())return this.#o(o,e,t);if(i.isVirtualNode){const s=this.node.getInputLink(o);if(s){const{inputNode:a}=s.resolve(this.graph);if(!a)throw new ut(`Virtual node failed to resolve parent [${this.id}] slot [${o}]`);const r=[...this.subgraphNodePath,a.id].join(":"),l=this.nodesByExecutionId.get(r);if(!l)throw new Error(`No input node DTO found for id [${a.id}]`);return l.resolveInput(s.target_slot,t,e)}return}return{node:this,origin_id:this.id,origin_slot:o}}#t(o,e){const{inputs:t}=this,n=t[o],i=this.node.outputs[o].type;if(e==="*"||e==="")return t.length>o?o:0;if(n&&_.isValidConnection(n.type,i)&&_.isValidConnection(n.type,e))return o;const s=t.findIndex(a=>a.type===e);return s!==-1?s:t.findIndex(a=>_.isValidConnection(a.type,i)&&_.isValidConnection(a.type,e))}#o(o,e,t){const{node:n}=this,i=n.outputs.at(o);if(!i)throw new Ut(`No output found for flattened id [${this.id}] slot [${o}]`);if(!n.isSubgraphNode())throw new TypeError(`Node is not a subgraph node: ${n.id}`);const s=n.resolveSubgraphOutputLink(o);if(!s)return;const a=s.outputNode;if(!a)throw new Error(`No output node found for id [${this.id}] slot [${o}] ${i.name}`);const r=[...this.subgraphNodePath,n.id,a.id].join(":"),l=this.nodesByExecutionId.get(r);if(!l)throw new Error(`No inner node DTO found for id [${r}]`);return l.resolveOutput(s.link.origin_slot,e,t)}},An=new Image;An.src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' width='16' height='16'%3E%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3E%3Cpath stroke='white' stroke-linecap='round' stroke-width='1.3' d='M9.18613 3.09999H6.81377M9.18613 12.9H7.55288c-3.08678 0-5.35171-2.99581-4.60305-6.08843l.3054-1.26158M14.7486 2.1721l-.5931 2.45c-.132.54533-.6065.92789-1.1508.92789h-2.2993c-.77173 0-1.33797-.74895-1.1508-1.5221l.5931-2.45c.132-.54533.6065-.9279 1.1508-.9279h2.2993c.7717 0 1.3379.74896 1.1508 1.52211Zm-8.3033 0-.59309 2.45c-.13201.54533-.60646.92789-1.15076.92789H2.4021c-.7717 0-1.33793-.74895-1.15077-1.5221l.59309-2.45c.13201-.54533.60647-.9279 1.15077-.9279h2.29935c.77169 0 1.33792.74896 1.15076 1.52211Zm8.3033 9.8-.5931 2.45c-.132.5453-.6065.9279-1.1508.9279h-2.2993c-.77173 0-1.33797-.749-1.1508-1.5221l.5931-2.45c.132-.5453.6065-.9279 1.1508-.9279h2.2993c.7717 0 1.3379.7489 1.1508 1.5221Z'/%3E%3C/svg%3E %3C/svg%3E";var gt=class extends q{static{h(this,"SubgraphNode")}type;isVirtualNode=!0;get rootGraph(){return this.graph.rootGraph}get displayType(){return"Subgraph node"}isSubgraphNode(){return!0}widgets=[];#e=new AbortController;constructor(o,e,t){super(e.name,e.id),this.graph=o,this.subgraph=e;const n=this.subgraph.events,{signal:i}=this.#e;n.addEventListener("input-added",s=>{const a=s.detail.input,{name:r,type:l}=a,d=this.inputs.find(p=>p.name==r);if(d){const p=a.linkIds[0],{inputNode:m,input:g}=e.links[p].resolve(e),f=m?.widgets?.find?.(y=>y.name==r);f&&this.#o(a,d,f,g?.widget);return}const u=this.addInput(r,l);this.#t(a,u)},{signal:i}),n.addEventListener("removing-input",s=>{const a=s.detail.input._widget;a&&this.ensureWidgetRemoved(a),this.removeInput(s.detail.index),this.setDirtyCanvas(!0,!0)},{signal:i}),n.addEventListener("output-added",s=>{const{name:a,type:r}=s.detail.output;this.addOutput(a,r)},{signal:i}),n.addEventListener("removing-output",s=>{this.removeOutput(s.detail.index),this.setDirtyCanvas(!0,!0)},{signal:i}),n.addEventListener("renaming-input",s=>{const{index:a,newName:r}=s.detail,l=this.inputs.at(a);if(!l)throw new Error("Subgraph input not found");l.label=r,l._widget&&(l._widget.label=r)},{signal:i}),n.addEventListener("renaming-output",s=>{const{index:a,newName:r}=s.detail,l=this.outputs.at(a);if(!l)throw new Error("Subgraph output not found");l.label=r},{signal:i}),this.type=e.id,this.configure(t),this.addTitleButton({name:"enter_subgraph",text:"",yOffset:0,xOffset:-10,fontSize:16})}onTitleButtonClick(o,e){o.name==="enter_subgraph"?e.openSubgraph(this.subgraph,this):super.onTitleButtonClick(o,e)}#t(o,e){e._listenerController&&typeof e._listenerController.abort=="function"&&e._listenerController.abort(),e._listenerController=new AbortController;const{signal:t}=e._listenerController;o.events.addEventListener("input-connected",n=>{if(e._widget)return;const i=o._widget;if(!i)return;const s=n.detail.input.widget;this.#o(o,e,i,s)},{signal:t}),o.events.addEventListener("input-disconnected",()=>{o.getConnectedWidgets().length>0||(this.removeWidgetByName(e.name),delete e.pos,delete e.widget,e._widget=void 0)},{signal:t})}configure(o){for(const e of this.inputs)e._listenerController&&typeof e._listenerController.abort=="function"&&e._listenerController.abort();this.inputs.length=0,this.inputs.push(...this.subgraph.inputNode.slots.map(e=>new Be({name:e.name,localized_name:e.localized_name,label:e.label,type:e.type,link:null},this))),this.outputs.length=0,this.outputs.push(...this.subgraph.outputNode.slots.map(e=>new mt({name:e.name,localized_name:e.localized_name,label:e.label,type:e.type,links:null},this))),super.configure(o)}_internalConfigureAfterSlots(){this.widgets.length=0;for(const o of this.inputs){const e=this.subgraph.inputNode.slots.find(t=>t.name===o.name);if(!e){console.warn(`[SubgraphNode.configure] No subgraph input found for input ${o.name}, skipping`);continue}this.#t(e,o);for(const t of e.linkIds){const n=this.subgraph.getLink(t);if(!n){console.warn(`[SubgraphNode.configure] No link found for link ID ${t}`,this);continue}const{inputNode:i}=n.resolve(this.subgraph);if(!i){console.warn("Failed to resolve inputNode",n,this);continue}const s=i.inputs.find(r=>r.link===t);if(!s){console.warn("Failed to find corresponding input",n,i);continue}const a=i.getWidgetFromSlot(s);if(a){this.#o(e,o,a,s.widget);break}}}}#o(o,e,t,n){const i=Ct(t,this).createCopyForNode(this);t instanceof En&&(i.options.nodeType??=t.node.type),Object.assign(i,{get name(){return o.name},set name(a){console.warn("Promoted widget: setting name is not allowed",this,a)},get localized_name(){return o.localized_name},set localized_name(a){console.warn("Promoted widget: setting localized_name is not allowed",this,a)},get label(){return o.label},set label(a){console.warn("Promoted widget: setting label is not allowed",this,a)},get tooltip(){return t.tooltip},set tooltip(a){console.warn("Promoted widget: setting tooltip is not allowed",this,a)}});const s=this.inputs.filter(a=>a.widget).length;this.widgets.splice(s,0,i),this.subgraph.events.dispatch("widget-promoted",{widget:i,subgraphNode:this}),e.widget??={name:o.name},e.widget.name=o.name,n&&Object.setPrototypeOf(e.widget,n),e._widget=i}addInput(o,e,t={}){return super.addInput(o,e,t)}getInputLink(o){const e=this.subgraph.outputNode.slots[o].getLinks().at(0);if(!e)return console.warn(`SubgraphNode.getInputLink: no inner link found for slot ${o}`),null;const t=z.create(e);return t.origin_id=`${this.id}:${e.origin_id}`,t.origin_slot=e.origin_slot,t}resolveSubgraphInputLinks(o){const e=this.subgraph.inputNode.slots[o],t=e.getLinks();return t.length===0?(console.warn(`[SubgraphNode.resolveSubgraphInputLinks] No inner links found for input slot [${o}] ${e.name}`,this),[]):t.map(n=>n.resolve(this.subgraph))}resolveSubgraphOutputLink(o){const e=this.subgraph.outputNode.slots[o],t=e.getLinks().at(0);if(t)return t.resolve(this.subgraph);console.warn(`[SubgraphNode.resolveSubgraphOutputLink] No inner link found for output slot [${o}] ${e.name}`,this)}getInnerNodes(o,e=[],t=[],n=new Set){if(n.has(this)){const r=`${this.id}${this.title?` (${this.title})`:""}`,l=`'${this.subgraph.name||"Unnamed Subgraph"}'`,d=e.length;throw new Qt(`Circular reference detected at depth ${d} in node ${r} of subgraph ${l}. This creates an infinite loop in the subgraph hierarchy.`)}n.add(this);const i=[...e,this.id],s=this.graph.rootGraph.resolveSubgraphIdPath(e).at(-1),a=new Po(this,e,o,s);o.set(a.id,a);for(const r of this.subgraph.nodes)if("getInnerNodes"in r&&r.getInnerNodes)r.getInnerNodes(o,i,t,new Set(n));else{const l=new Po(r,i,o,this);o.set(l.id,l),t.push(l)}return t}removeWidgetByName(o){const e=this.widgets.find(t=>t.name===o);e&&this.subgraph.events.dispatch("widget-demoted",{widget:e,subgraphNode:this}),super.removeWidgetByName(o)}ensureWidgetRemoved(o){this.widgets.includes(o)&&this.subgraph.events.dispatch("widget-demoted",{widget:o,subgraphNode:this}),super.ensureWidgetRemoved(o)}onRemoved(){this.#e.abort();for(const o of this.widgets)"isProxyWidget"in o&&o.isProxyWidget||this.subgraph.events.dispatch("widget-demoted",{widget:o,subgraphNode:this});for(const o of this.inputs)o._listenerController&&typeof o._listenerController.abort=="function"&&o._listenerController.abort()}drawTitleBox(o,{scale:e,low_quality:t=!1,title_height:n=_.NODE_TITLE_HEIGHT,box_size:i=10}){if(this.onDrawTitleBox){this.onDrawTitleBox(o,n,this.renderingSize,e);return}o.save(),o.fillStyle="#3b82f6",o.beginPath(),o.roundRect(6,-24.5,22,20,5),o.fill(),t||(o.translate(25,23),o.scale(-1.5,1.5),o.drawImage(An,0,-n,i,i)),o.restore()}serialize(){for(let o=0;o<this.widgets.length;o++){const e=this.widgets[o],t=this.inputs.find(n=>n.name===e.name);if(t){const n=this.subgraph.inputNode.slots.find(i=>i.name===t.name);if(n){const i=n.getConnectedWidgets();for(const s of i)s.value=e.value}}}return super.serialize()}clone(){const o=super.clone();return this.properties.proxyWidgets=this.properties.proxyWidgets,o}};function Dn(o){const e=o?.find(a=>a);if(!e)return null;let t=e,n=e,i=e,s=e;for(const a of o){if(!a)continue;const[r,l]=a.pos,[d,u]=a.size;l<t.pos[1]&&(t=a),r+d>n.pos[0]+n.size[0]&&(n=a),l+u>i.pos[1]+i.size[1]&&(i=a),r<s.pos[0]&&(s=a)}return{top:t,right:n,bottom:i,left:s}}h(Dn,"getBoundaryNodes");function Rw(o,e){const t=o?.length;if(!(t>1))return[];const n=e?0:1;let i=0,s=-1/0;for(const u of o){i+=u.size[n];const p=u.pos[n]+u.size[n];p>s&&(s=p)}const a=[...o].sort((u,p)=>u.pos[n]-p.pos[n]),r=a[0].pos[n],l=(s-r-i)/(t-1);let d=r;for(let u=0;u<t;u++){const p=a[u];p.pos[n]=d+l*u,d+=p.size[n]}return a.map(u=>({node:u,newPos:{x:u.pos[0],y:u.pos[1]}}))}h(Rw,"distributeNodes");function Wt(o,e,t){if(!o)return[];const n=t===void 0?Dn(o):{top:t,right:t,bottom:t,left:t};if(n===null)return[];const i=o.map(s=>{switch(e){case"right":return{node:s,newPos:{x:n.right.pos[0]+n.right.size[0]-s.size[0],y:s.pos[1]}};case"left":return{node:s,newPos:{x:n.left.pos[0],y:s.pos[1]}};case"top":return{node:s,newPos:{x:s.pos[0],y:n.top.pos[1]}};case"bottom":return{node:s,newPos:{x:s.pos[0],y:n.bottom.pos[1]+n.bottom.size[1]-s.size[1]}}}});for(const{node:s,newPos:a}of i)s.pos[0]=a.x,s.pos[1]=a.y;return i}h(Wt,"alignNodes");function Fw(o){return o===_.EVENT?_.EVENT_LINK_COLOR:_.CONNECTING_LINK_COLOR}h(Fw,"resolveConnectingLinkColor");var Gt={NE:"nesw-resize",SE:"nwse-resize",SW:"nesw-resize",NW:"nwse-resize"},zw=new X,Bw=[0,0],Vw=new X,$e=new X,Te=new X,ce=class L{static{h(this,"LGraphCanvas")}static DEFAULT_BACKGROUND_IMAGE="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=";static DEFAULT_EVENT_LINK_COLOR="#A86";static link_type_colors={"-1":L.DEFAULT_EVENT_LINK_COLOR,number:"#AAA",node:"#DCA"};static gradients={};static search_limit=-1;static node_colors={red:{color:"#322",bgcolor:"#533",groupcolor:"#A88"},brown:{color:"#332922",bgcolor:"#593930",groupcolor:"#b06634"},green:{color:"#232",bgcolor:"#353",groupcolor:"#8A8"},blue:{color:"#223",bgcolor:"#335",groupcolor:"#88A"},pale_blue:{color:"#2a363b",bgcolor:"#3f5159",groupcolor:"#3f789e"},cyan:{color:"#233",bgcolor:"#355",groupcolor:"#8AA"},purple:{color:"#323",bgcolor:"#535",groupcolor:"#a1309b"},yellow:{color:"#432",bgcolor:"#653",groupcolor:"#b58b2a"},black:{color:"#222",bgcolor:"#000",groupcolor:"#444"}};static _measureText;state={draggingItems:!1,draggingCanvas:!1,readOnly:!1,hoveringOver:te.Nothing,shouldSetCursor:!0,selectionChanged:!1};#e;get subgraph(){return this.#e}set subgraph(e){e!==this.#e&&(this.#e=e,e&&this.dispatch("litegraph:set-graph",{oldGraph:this.#e,newGraph:e}))}fpsInfoLocation;dispatch(e,t){const n=new CustomEvent(e,{detail:t,bubbles:!0});return this.canvas.dispatchEvent(n)}dispatchEvent(e,t){this.canvas.dispatchEvent(new CustomEvent(e,{detail:t}))}#t(){if(!this.state.shouldSetCursor)return;const e=te.Node|te.RerouteSlot|te.SubgraphIoNode|te.SubgraphIoSlot;let t="default";this.state.draggingCanvas?t="grabbing":this.state.readOnly?t="grab":this.pointer.resizeDirection?t=Gt[this.pointer.resizeDirection]??Gt.SE:this.state.hoveringOver&e?t="crosshair":this.state.hoveringOver&te.Reroute&&(t="grab"),this.canvas.style.cursor=t}_previously_dragging_canvas=null;get read_only(){return this.state.readOnly}set read_only(e){this.state.readOnly=e,this.#t()}get isDragging(){return this.state.draggingItems}set isDragging(e){this.state.draggingItems=e}get hoveringOver(){return this.state.hoveringOver}set hoveringOver(e){this.state.hoveringOver=e,this.#t()}get pointer_is_down(){return this.pointer.isDown}get pointer_is_double(){return this.pointer.isDouble}get dragging_canvas(){return this.state.draggingCanvas}set dragging_canvas(e){this.state.draggingCanvas=e,this.#t()}get title_text_font(){return`${_.NODE_TEXT_SIZE}px ${_.NODE_FONT}`}get inner_text_font(){return`normal ${_.NODE_SUBTEXT_SIZE}px ${_.NODE_FONT}`}#o=0;get maximumFps(){return this.#o>Number.EPSILON?this.#o/1e3:0}set maximumFps(e){this.#o=e>Number.EPSILON?1e3/e:0}get round_radius(){return _.ROUND_RADIUS}set round_radius(e){_.ROUND_RADIUS=e}_lowQualityZoomThreshold=0;_isLowQuality=!1;updateLowQualityThreshold(){if(this._min_font_size_for_lod===0){this._lowQualityZoomThreshold=0,this._isLowQuality=!1;return}const e=_.NODE_TEXT_SIZE,t=Math.sqrt(window.devicePixelRatio||1);this._lowQualityZoomThreshold=this._min_font_size_for_lod/(e*t),this._isLowQuality=this.ds.scale<this._lowQualityZoomThreshold}get low_quality(){return this._isLowQuality}options;background_image;ds;pointer;zoom_modify_alpha;zoom_speed;node_title_color;default_link_color;default_connection_color;default_connection_color_byType;default_connection_color_byTypeOff;colourGetter={getConnectedColor:h(e=>this.default_connection_color_byType[e]||this.default_connection_color.output_on,"getConnectedColor"),getDisconnectedColor:h(e=>this.default_connection_color_byTypeOff[e]||this.default_connection_color_byType[e]||this.default_connection_color.output_off,"getDisconnectedColor")};highquality_render;use_gradients;editor_alpha;pause_rendering;clear_background;clear_background_color;render_only_selected;show_info;allow_dragcanvas;allow_dragnodes;allow_interaction;multi_select;allow_searchbox;allow_reconnect_links;align_to_grid;drag_mode;dragging_rectangle;filter;set_canvas_dirty_on_mouse_event;always_render_background;render_shadows;render_canvas_border;render_connections_shadows;render_connections_border;render_curved_connections;render_connection_arrows;render_collapsed_slots;render_execution_order;render_link_tooltip;linkMarkerShape=re.Circle;links_render_mode;_min_font_size_for_lod=8;get min_font_size_for_lod(){return this._min_font_size_for_lod}set min_font_size_for_lod(e){this._min_font_size_for_lod!==e&&(this._min_font_size_for_lod=e,this.updateLowQualityThreshold())}mouse;graph_mouse;canvas_mouse;onSearchBox;onSearchBoxSelection;onMouse;onDrawBackground;onDrawForeground;connections_width;current_node;node_widget;over_link_center;last_mouse_position;visible_area;renderedPaths=new Set;visible_links=[];connecting_links;linkConnector=new Mw(e=>this.connecting_links=e);viewport;autoresize;static active_canvas;frame=0;last_draw_time=0;render_time=0;fps=0;selected_nodes={};selectedItems=new Set;resizingGroup=null;selected_group=null;visible_nodes=[];#n=new Set;node_over;node_capturing_input;highlighted_links={};#s=new Set;dirty_canvas=!0;dirty_bgcanvas=!0;dirty_nodes=new Map;dirty_area;node_in_panel;last_mouse=[0,0];last_mouseclick=0;graph;get _graph(){if(!this.graph)throw new N;return this.graph}canvas;bgcanvas;ctx;_events_binded;bgctx;is_rendering;block_click;last_click_position;resizing_node;selected_group_resizing;last_mouse_dragging;onMouseDown;_highlight_pos;_highlight_input;node_panel;options_panel;_bg_img;_pattern;_pattern_img;bg_tint;prompt_box;search_box;SELECTED_NODE;NODEPANEL_IS_OPEN;#i;#d=!1;linkRenderer=null;dragZoomEnabled=!1;#a=null;liveSelection=!1;static active_node;onClear;onNodeMoved;onSelectionChange;onDrawLinkTooltip;onDrawOverlay;onRenderBackground;onNodeDblClicked;onShowNodePanel;onNodeSelected;onNodeDeselected;onRender;constructor(e,t,n){n||={},this.options=n,this.background_image=L.DEFAULT_BACKGROUND_IMAGE,this.ds=new tn(e),this.pointer=new ms(e),this.ds.onChanged=(i,s)=>{this._lowQualityZoomThreshold>0&&(this._isLowQuality=i<this._lowQualityZoomThreshold)},t&&(this.linkRenderer=new yo(!1)),this.linkConnector.events.addEventListener("link-created",()=>this.#r()),this.linkConnector.events.addEventListener("reset",()=>{this.connecting_links=null,this.dirty_bgcanvas=!0}),this.linkConnector.events.addEventListener("dropped-on-canvas",i=>{if(!this.connecting_links)return;const s=i.detail;this.emitEvent({subType:"empty-release",originalEvent:s,linkReleaseContext:{links:this.connecting_links}});const a=this.linkConnector.renderLinks[0];if(_.release_link_on_empty_shows_menu){const r=this.linkConnector.state.connectingTo==="input"?{node_from:a.node,slot_from:a.fromSlot,type_filter_in:a.fromSlot.type}:{node_to:a.node,slot_to:a.fromSlot,type_filter_out:a.fromSlot.type},l=a.fromReroute?.id;"shiftKey"in s&&s.shiftKey?this.allow_searchbox&&this.showSearchBox(s,r):this.linkConnector.state.connectingTo==="input"?this.showConnectionMenu({nodeFrom:a.node,slotFrom:a.fromSlot,e:s,afterRerouteId:l}):this.showConnectionMenu({nodeTo:a.node,slotTo:a.fromSlot,e:s,afterRerouteId:l})}}),this.zoom_modify_alpha=!0,this.zoom_speed=1.1,this.node_title_color=_.NODE_TITLE_COLOR,this.default_link_color=_.LINK_COLOR,this.default_connection_color={input_off:"#778",input_on:"#7F7",output_off:"#778",output_on:"#7F7"},this.default_connection_color_byType={},this.default_connection_color_byTypeOff={},this.highquality_render=!0,this.use_gradients=!1,this.editor_alpha=1,this.pause_rendering=!1,this.clear_background=!0,this.clear_background_color="#222",this.render_only_selected=!0,this.show_info=!0,this.allow_dragcanvas=!0,this.allow_dragnodes=!0,this.allow_interaction=!0,this.multi_select=!1,this.allow_searchbox=!0,this.allow_reconnect_links=!0,this.align_to_grid=!1,this.drag_mode=!1,this.dragging_rectangle=null,this.filter=null,this.set_canvas_dirty_on_mouse_event=!0,this.always_render_background=!1,this.render_shadows=!0,this.render_canvas_border=!0,this.render_connections_shadows=!1,this.render_connections_border=!0,this.render_curved_connections=!1,this.render_connection_arrows=!1,this.render_collapsed_slots=!0,this.render_execution_order=!1,this.render_link_tooltip=!0,this.links_render_mode=ie.SPLINE_LINK,this.mouse=[0,0],this.graph_mouse=[0,0],this.canvas_mouse=this.graph_mouse,this.connections_width=3,this.current_node=null,this.node_widget=null,this.last_mouse_position=[0,0],this.visible_area=this.ds.visible_area,this.connecting_links=null,this.viewport=n.viewport,this.graph=t,t?.attachCanvas(this),this.canvas=void 0,this.bgcanvas=void 0,this.ctx=void 0,this.setCanvas(e,n.skip_events),this.clear(),L._measureText=(i,s=this.inner_text_font)=>{const{ctx:a}=this,{font:r}=a;try{return a.font=s,a.measureText(i).width}finally{a.font=r}},n.skip_render||this.startRendering(),this.autoresize=n.autoresize??!1,this.updateLowQualityThreshold()}static onGroupAdd(e,t,n){const i=L.active_canvas,s=new _.LGraphGroup;if(s.pos=i.convertEventToCanvasOffset(n),!i.graph)throw new N;i.graph.add(s)}static getBoundaryNodes(e){return Dn(Array.isArray(e)?e:Object.values(e))??{top:null,right:null,bottom:null,left:null}}static alignNodes(e,t,n){const i=Wt(Object.values(e),t,n);L.active_canvas.repositionNodesVueMode(i),L.active_canvas.setDirty(!0,!0)}static onNodeAlign(e,t,n,i,s){new _.ContextMenu(["Top","Bottom","Left","Right"],{event:n,callback:a,parentMenu:i});function a(r){const l=Wt(Object.values(L.active_canvas.selected_nodes),r.toLowerCase(),s);L.active_canvas.repositionNodesVueMode(l),L.active_canvas.setDirty(!0,!0)}h(a,"inner_clicked")}static onGroupAlign(e,t,n,i){new _.ContextMenu(["Top","Bottom","Left","Right"],{event:n,callback:s,parentMenu:i});function s(a){const r=Wt(Object.values(L.active_canvas.selected_nodes),a.toLowerCase());L.active_canvas.repositionNodesVueMode(r),L.active_canvas.setDirty(!0,!0)}h(s,"inner_clicked")}static createDistributeMenu(e,t,n,i){new _.ContextMenu(["Vertically","Horizontally"],{event:n,callback:s,parentMenu:i});function s(a){const r=L.active_canvas,l=Rw(Object.values(r.selected_nodes),a==="Horizontally");r.repositionNodesVueMode(l),r.setDirty(!0,!0)}h(s,"inner_clicked")}static onMenuAdd(e,t,n,i,s){const a=L.active_canvas,{graph:r}=a;if(!r)return;return l("",i),!1;function l(d,u){if(!r)return;const p=_.getNodeTypesCategories(a.filter||r.filter).filter(f=>f.startsWith(d)),m=[];for(const f of p){if(!f)continue;const y=new RegExp(`^(${d})`),b=f.replace(y,"").split("/",1)[0],v=d===""?`${b}/`:`${d}${b}/`;let k=b;k.includes("::")&&(k=k.split("::",2)[1]),m.findIndex(w=>w.value===v)===-1&&m.push({value:v,content:k,has_submenu:!0,callback:h(function(w,S,E,C){l(w.value,C)},"callback")})}const g=_.getNodeTypesInCategory(d.slice(0,-1),a.filter||r.filter);for(const f of g){if(f.skip_list)continue;const y={value:f.type,content:f.title,has_submenu:!1,callback:h(function(b,v,k,w){if(!a.graph)throw new N;const S=w.getFirstEvent();a.graph.beforeChange();const E=_.createNode(b.value);if(E){if(!S)throw new TypeError("Context menu event was null. This should not occur in normal usage.");E.pos=a.convertEventToCanvasOffset(S),a.graph.add(E)}else console.warn("Failed to create node of type:",b.value);s?.(E),a.graph.afterChange()},"callback")};m.push(y)}new _.ContextMenu(m,{event:n,parentMenu:u})}h(l,"inner_onMenuAdded")}static onMenuCollapseAll(){}static onMenuNodeEdit(){}static showMenuNodeOptionalOutputs(e,t,n,i,s){if(!s)return;const a=L.active_canvas;let r=[];_.do_add_triggers_slots&&s.findOutputSlot("onExecuted")==-1&&r.push({content:"On Executed",value:["onExecuted",_.EVENT,{nameLocked:!0}],className:"event"});const l=s.onMenuNodeOutputs?.(r);if(l&&(r=l),!r.length)return;new _.ContextMenu(r,{event:n,callback:d,parentMenu:i,node:s});function d(u,p,m,g){if(!s||!u||typeof u=="string"||(u.callback&&u.callback.call(this,s,u,m,g),!u.value))return;const f=u.value[1];if(f&&(typeof f=="object"||Array.isArray(f))){const b=[];for(const v in f)b.push({content:v,value:f[v]});return new _.ContextMenu(b,{event:m,callback:d,parentMenu:i,node:s}),!1}const{graph:y}=s;if(!y)throw new N;y.beforeChange(),s.addOutput(u.value[0],u.value[1],u.value[2]),s.onNodeOutputAdd?.(u.value),a.setDirty(!0,!0),y.afterChange()}return h(d,"inner_clicked"),!1}static onShowMenuNodeProperties(e,t,n,i,s){if(!s||!s.properties)return;const a=L.active_canvas,r=[];for(const d in s.properties){e=s.properties[d]!==void 0?s.properties[d]:" ",typeof e=="object"&&(e=JSON.stringify(e));const u=s.getPropertyInfo(d);(u.type=="enum"||u.type=="combo")&&(e=L.getPropertyPrintableValue(e,u.values)),e=L.decodeHTML($t(e)),r.push({content:`<span class='property_name'>${u.label||d}</span><span class='property_value'>${e}</span>`,value:d})}if(!r.length)return;new _.ContextMenu(r,{event:n,callback:l,parentMenu:i,node:s});function l(d){if(!s||typeof d=="string"||!d?.value)return;const u=this.root.getBoundingClientRect();a.showEditPropertyValue(s,d.value,{position:[u.left,u.top]})}return h(l,"inner_clicked"),!1}static decodeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}static onMenuResizeNode(e,t,n,i,s){if(!s)return;const a=h(function(l){l.setSize(l.computeSize())},"fApplyMultiNode"),r=L.active_canvas;if(!r.selected_nodes||Object.keys(r.selected_nodes).length<=1)a(s);else for(const l in r.selected_nodes)a(r.selected_nodes[l]);r.setDirty(!0,!0)}static onShowPropertyEditor(e,t,n,i,s){const a=e.property||"title",r=s[a],l=document.createElement("span");l.className="name",l.textContent=a;const d=document.createElement("input");Object.assign(d,{type:"text",className:"value",autofocus:!0});const u=document.createElement("button");u.textContent="OK";const p=Object.assign(document.createElement("div"),{is_modified:!1,className:"graphdialog",close:h(()=>p.remove(),"close")});p.append(l,d,u),d.value=String(r),d.addEventListener("blur",function(){this.focus()}),d.addEventListener("keydown",S=>{if(p.is_modified=!0,S.key=="Escape")p.close();else if(S.key=="Enter")k();else if(!S.target||!("localName"in S.target)||S.target.localName!="textarea")return;S.preventDefault(),S.stopPropagation()});const m=L.active_canvas,g=m.canvas,f=g.getBoundingClientRect(),y=f?-20-f.left:-20,b=f?-20-f.top:-20;if(n?(p.style.left=`${n.clientX+y}px`,p.style.top=`${n.clientY+b}px`):(p.style.left=`${g.width*.5+y}px`,p.style.top=`${g.height*.5+b}px`),u.addEventListener("click",k),g.parentNode==null)throw new TypeError("canvasEl.parentNode was null");g.parentNode.append(p),d.focus();let v;p.addEventListener("mouseleave",function(){_.dialog_close_on_mouse_leave&&!p.is_modified&&_.dialog_close_on_mouse_leave&&(v=setTimeout(p.close,_.dialog_close_on_mouse_leave_delay))}),p.addEventListener("mouseenter",function(){_.dialog_close_on_mouse_leave&&v&&clearTimeout(v)});function k(){d&&w(d.value)}h(k,"inner");function w(S){e.type=="Number"?S=Number(S):e.type=="Boolean"&&(S=!!S),s[a]=S,p.remove(),m.setDirty(!0,!0)}h(w,"setValue")}static getPropertyPrintableValue(e,t){if(!t||Array.isArray(t))return String(e);if(typeof t=="object"){let n="";for(const i in t)if(t[i]==e){n=i;break}return`${String(e)} (${n})`}}static onMenuNodeCollapse(e,t,n,i,s){if(!s.graph)throw new N;s.graph.beforeChange();const a=h(function(l){l.collapse()},"fApplyMultiNode"),r=L.active_canvas;if(!r.selected_nodes||Object.keys(r.selected_nodes).length<=1)a(s);else for(const l in r.selected_nodes)a(r.selected_nodes[l]);s.graph.afterChange()}static onMenuToggleAdvanced(e,t,n,i,s){if(!s.graph)throw new N;s.graph.beforeChange();const a=h(function(l){l.toggleAdvanced()},"fApplyMultiNode"),r=L.active_canvas;if(!r.selected_nodes||Object.keys(r.selected_nodes).length<=1)a(s);else for(const l in r.selected_nodes)a(r.selected_nodes[l]);s.graph.afterChange()}static onMenuNodeMode(e,t,n,i,s){new _.ContextMenu(_.NODE_MODES,{event:n,callback:a,parentMenu:i,node:s});function a(r){if(!s)return;const l=Object.values(_.NODE_MODES).indexOf(r),d=h(function(p){l!==-1&&_.NODE_MODES[l]?p.changeMode(l):(console.warn(`unexpected mode: ${r}`),p.changeMode(H.ALWAYS))},"fApplyMultiNode"),u=L.active_canvas;if(!u.selected_nodes||Object.keys(u.selected_nodes).length<=1)d(s);else for(const p in u.selected_nodes)d(u.selected_nodes[p])}return h(a,"inner_clicked"),!1}static onMenuNodeColors(e,t,n,i,s){if(!s)throw"no node for color";const a=[];a.push({value:null,content:"<span style='display: block; padding-left: 4px;'>No color</span>"});for(const l in L.node_colors){const d=L.node_colors[l];e={value:l,content:`<span style='display: block; color: #999; padding-left: 4px; border-left: 8px solid ${d.color}; background-color:${d.bgcolor}'>${l}</span>`},a.push(e)}new _.ContextMenu(a,{event:n,callback:r,parentMenu:i,node:s});function r(l){if(!s)return;const d=h(function(p){const m=l.value?L.node_colors[l.value]:null;p.setColorOption(m)},"fApplyColor"),u=L.active_canvas;if(!u.selected_nodes||Object.keys(u.selected_nodes).length<=1)d(s);else for(const p in u.selected_nodes)d(u.selected_nodes[p]);u.setDirty(!0,!0)}return h(r,"inner_clicked"),!1}static onMenuNodeShapes(e,t,n,i,s){if(!s)throw"no node passed";new _.ContextMenu(_.VALID_SHAPES,{event:n,callback:a,parentMenu:i,node:s});function a(r){if(!s)return;if(!s.graph)throw new N;s.graph.beforeChange();const l=h(function(u){u.shape=r},"fApplyMultiNode"),d=L.active_canvas;if(!d.selected_nodes||Object.keys(d.selected_nodes).length<=1)l(s);else for(const u in d.selected_nodes)l(d.selected_nodes[u]);s.graph.afterChange(),d.setDirty(!0)}return h(a,"inner_clicked"),!1}static onMenuNodeRemove(){L.active_canvas.deleteSelected()}static onMenuNodeClone(e,t,n,i,s){const a=L.active_canvas,r=a.selectedItems.size?[...a.selectedItems]:[s];r.length&&L.cloneNodes(r)}static cloneNodes(e){const t=L.active_canvas;let n=1/0,i=1/0;for(const s of e){if(s.pos==null)throw new TypeError("Invalid node encountered on clone. `pos` was null.");n=Math.min(n,s.pos[0]),i=Math.min(i,s.pos[1])}return t._deserializeItems(t._serializeItems(e),{position:[n+5,i+5]})}clear(){this.frame=0,this.last_draw_time=0,this.render_time=0,this.fps=0,this.dragging_rectangle=null,this.selected_nodes={},this.selected_group=null,this.selectedItems.clear(),this.state.selectionChanged=!0,this.onSelectionChange?.(this.selected_nodes),this.visible_nodes=[],this.node_over=void 0,this.node_capturing_input=null,this.connecting_links=null,this.highlighted_links={},this.dragging_canvas=!1,this.#r(),this.dirty_area=null,this.node_in_panel=null,this.node_widget=null,this.last_mouse=[0,0],this.last_mouseclick=0,this.pointer.reset(),this.visible_area.set([0,0,0,0]),this.onClear?.()}setGraph(e){const{graph:t}=this;e!==t&&(this.clear(),e.attachCanvas(this),this.linkRenderer=new yo(!1),this.dispatch("litegraph:set-graph",{newGraph:e,oldGraph:t}),this.#r())}openSubgraph(e,t){const{graph:n}=this;if(!n)throw new N;const i={bubbles:!0,detail:{subgraph:e,closingGraph:n,fromNode:t},cancelable:!0};this.canvas.dispatchEvent(new CustomEvent("subgraph-opening",i))&&(this.clear(),this.subgraph=e,this.setGraph(e),this.canvas.dispatchEvent(new CustomEvent("subgraph-opened",i)))}getCurrentGraph(){return this.graph}#c(e){if(typeof e=="string"){const t=document.getElementById(e);if(!(t instanceof HTMLCanvasElement))throw"Error validating LiteGraph canvas: Canvas element not found";return t}return e}setCanvas(e,t){const n=this.#c(e);if(n===this.canvas||(!n&&this.canvas&&!t&&this.unbindEvents(),this.canvas=n,this.ds.element=n,this.pointer.element=n,!n))return;n.className+=" lgraphcanvas",n.data=this,this.bgcanvas=document.createElement("canvas"),this.bgcanvas.width=this.canvas.width,this.bgcanvas.height=this.canvas.height;const i=n.getContext?.("2d");if(i==null)throw n.localName!="canvas"?`Element supplied for LGraphCanvas must be a <canvas> element, you passed a ${n.localName}`:"This browser doesn't support Canvas";this.ctx=i,t||this.bindEvents()}_doNothing(e){return e.preventDefault(),!1}_doReturnTrue(e){return e.preventDefault(),!0}bindEvents(){if(this._events_binded){console.warn("LGraphCanvas: events already bound");return}const{canvas:e}=this,{document:t}=this.getCanvasWindow();this._mousedown_callback=this.processMouseDown.bind(this),this._mousewheel_callback=this.processMouseWheel.bind(this),this._mousemove_callback=this.processMouseMove.bind(this),this._mouseup_callback=this.processMouseUp.bind(this),this._mouseout_callback=this.processMouseOut.bind(this),this._mousecancel_callback=this.processMouseCancel.bind(this),e.addEventListener("pointerdown",this._mousedown_callback,!0),e.addEventListener("wheel",this._mousewheel_callback,!1),e.addEventListener("pointerup",this._mouseup_callback,!0),e.addEventListener("pointermove",this._mousemove_callback),e.addEventListener("pointerout",this._mouseout_callback),e.addEventListener("pointercancel",this._mousecancel_callback,!0),e.addEventListener("contextmenu",this._doNothing),this._key_callback=this.processKey.bind(this),e.addEventListener("keydown",this._key_callback,!0),t.addEventListener("keyup",this._key_callback,!0),e.addEventListener("dragover",this._doNothing,!1),e.addEventListener("dragend",this._doNothing,!1),e.addEventListener("dragenter",this._doReturnTrue,!1),this._events_binded=!0}unbindEvents(){if(!this._events_binded){console.warn("LGraphCanvas: no events bound");return}const{document:e}=this.getCanvasWindow(),{canvas:t}=this;t.removeEventListener("pointercancel",this._mousecancel_callback),t.removeEventListener("pointerout",this._mouseout_callback),t.removeEventListener("pointermove",this._mousemove_callback),t.removeEventListener("pointerup",this._mouseup_callback),t.removeEventListener("pointerdown",this._mousedown_callback),t.removeEventListener("wheel",this._mousewheel_callback),t.removeEventListener("keydown",this._key_callback),e.removeEventListener("keyup",this._key_callback),t.removeEventListener("contextmenu",this._doNothing),t.removeEventListener("dragenter",this._doReturnTrue),this._mousedown_callback=void 0,this._mousewheel_callback=void 0,this._key_callback=void 0,this._events_binded=!1}setDirty(e,t){e&&(this.dirty_canvas=!0),t&&(this.dirty_bgcanvas=!0)}#r(){this.dirty_canvas=!0,this.dirty_bgcanvas=!0}#l(){const{graph:e,linkConnector:t,pointer:n}=this;if(!e)throw new N;n.onDragEnd=i=>t.dropLinks(e,i),n.finally=()=>this.linkConnector.reset(!0)}getCanvasWindow(){if(!this.canvas)return window;const e=this.canvas.ownerDocument;return e.defaultView||e.parentWindow}startRendering(){if(this.is_rendering)return;this.is_rendering=!0,e.call(this);function e(){this.pause_rendering||this.draw();const t=this.getCanvasWindow();if(this.is_rendering)if(this.#o>0){const n=this.#o-(_.getTime()-this.last_draw_time);setTimeout(e.bind(this),Math.max(1,n))}else t.requestAnimationFrame(e.bind(this))}h(e,"renderFrame")}stopRendering(){this.is_rendering=!1}blockClick(){this.block_click=!0,this.last_mouseclick=0}getWidgetAtCursor(e){return e??=this.node_over,e?.getWidgetOnPos(this.graph_mouse[0],this.graph_mouse[1],!0)}updateMouseOverNodes(e,t){if(!this.graph)throw new N;const{pointer:n}=this,i=this.graph._nodes;for(const s of i)s.mouseOver&&e!=s&&(n.eDown||(n.resizeDirection=void 0),s.mouseOver=void 0,this._highlight_input=void 0,this._highlight_pos=void 0,this.linkConnector.overWidget=void 0,s.lostFocusAt=_.getTime(),this.node_over?.onMouseLeave?.(t),this.node_over=void 0,this.dirty_canvas=!0)}processMouseDown(e){if(this.dragZoomEnabled&&e.ctrlKey&&e.shiftKey&&!e.altKey&&e.buttons){this.#a={pos:[e.x,e.y],scale:this.ds.scale,readOnly:this.read_only},this.read_only=!0;return}const{graph:t,pointer:n}=this;if(this.adjustMouseEvent(e),e.isPrimary&&n.down(e),this.set_canvas_dirty_on_mouse_event&&(this.dirty_canvas=!0),!t)return;const i=this.getCanvasWindow();L.active_canvas=this;const s=e.clientX,a=e.clientY;if(this.ds.viewport=this.viewport,!(!this.viewport||yt(s,a,this.viewport)))return;const r=t.getNodeOnPos(e.canvasX,e.canvasY,this.visible_nodes)??void 0;if(this.mouse[0]=s,this.mouse[1]=a,this.graph_mouse[0]=e.canvasX,this.graph_mouse[1]=e.canvasY,this.last_click_position=[this.mouse[0],this.mouse[1]],n.isDouble=n.isDown&&e.isPrimary,n.isDown=!0,this.canvas.focus(),_.closeAllContextMenus(i),this.onMouse?.(e)!=!0){if(e.button===0&&!n.isDouble)this.#f(e,r);else if(e.button===1)this.#_(e,r);else if((e.button===2||n.isDouble)&&this.allow_interaction&&!this.read_only){const{linkConnector:l,subgraph:d}=this;if(d?.inputNode.containsPoint(this.graph_mouse))this.processSelect(d.inputNode,e,!0),d.inputNode.onPointerDown(e,n,l);else if(d?.outputNode.containsPoint(this.graph_mouse))this.processSelect(d.outputNode,e,!0),d.outputNode.onPointerDown(e,n,l);else{if(r)this.processSelect(r,e,!0);else if(this.links_render_mode!==ie.HIDDEN_LINK){const u=D.queryRerouteAtPoint({x:e.canvasX,y:e.canvasY});let p;u?p=t.getReroute(u.id):p=t.getRerouteOnPos(e.canvasX,e.canvasY,this.#s),p&&(e.altKey?n.onClick=m=>{m.altKey&&(p.selected&&(this.deselect(p),this.onSelectionChange?.(this.selected_nodes)),p.remove())}:this.processSelect(p,e,!0))}n.onClick??=()=>this.processContextMenu(r,e)}}this.last_mouse=[s,a],this.last_mouseclick=_.getTime(),this.last_mouse_dragging=!0,t.change(),(!i.document.activeElement||i.document.activeElement.nodeName.toLowerCase()!="input"&&i.document.activeElement.nodeName.toLowerCase()!="textarea")&&e.preventDefault(),e.stopPropagation(),this.onMouseDown?.(e)}}#u(e,t){const n=this.subgraph?.getIoNodeOnPos(e,t);if(n)return n;for(const i of this.#s)if(i.containsPoint([e,t]))return i;return this.graph?.getGroupTitlebarOnPos(e,t)}#f(e,t){const{pointer:n,graph:i,linkConnector:s,subgraph:a}=this;if(!i)throw new N;const r=e.canvasX,l=e.canvasY,d=e.ctrlKey||e.metaKey;if(d&&!e.altKey&&_.leftMouseClickBehavior==="panning"){this.#p(e,n,t);return}if(this.read_only){n.finally=()=>this.dragging_canvas=!1,this.dragging_canvas=!0;return}if(!_.vueNodesMode&&_.alt_drag_do_clone_nodes&&e.altKey&&!e.ctrlKey&&t&&this.allow_interaction){const u=this._deserializeItems(this._serializeItems([t]),{position:t.pos})?.created[0];if(!u)return;u.pos[0]+=5,u.pos[1]+=5,this.allow_dragnodes&&(n.onDragStart=p=>{this.#h(u,p)},n.onDragEnd=p=>this.#g(p));return}if(t&&(this.allow_interaction||t.flags.allow_interaction))this.#m(e,d,t);else{if(a){let b=function(v,k){return k.containsPoint([r,l])?(k.onPointerDown(e,n,s),n.onClick??=()=>v.processSelect(k,e),n.onDragStart??=()=>v.#h(k,n,!0),n.onDragEnd??=w=>v.#g(w),!0):!1};h(b,"processSubgraphIONode");const{inputNode:f,outputNode:y}=a;if(b(this,f)||b(this,y))return}if(this.links_render_mode!==ie.HIDDEN_LINK){const f=D.queryRerouteAtPoint({x:r,y:l});let y;f&&(y=i.getReroute(f.id));for(const b of this.#s){const v=y===b||b.containsPoint([r,l]);if(!(!b.isSlotHovered&&!v)){v&&(n.onClick=()=>this.processSelect(b,e),e.shiftKey||(n.onDragStart=k=>this.#h(b,k,!0),n.onDragEnd=k=>this.#g(k))),(b.isOutputHovered||v&&e.shiftKey)&&(s.dragFromReroute(i,b),this.#l()),b.isInputHovered&&(s.dragFromRerouteToOutput(i,b),this.#l()),b.hideSlots(),this.dirty_bgcanvas=!0;return}}}const{lineWidth:u}=this.ctx;this.ctx.lineWidth=this.connections_width+7;const p=Math.max(window?.devicePixelRatio??1,1),m=D.queryLinkSegmentAtPoint({x:r,y:l},this.ctx);for(const f of this.renderedPaths){const y=f._pos;if(!y)continue;let b=m&&f.id===(f instanceof J?m.rerouteId:m.linkId);if(!b&&f.path&&(b=this.ctx.isPointInStroke(f.path,r*p,l*p)),(e.shiftKey||e.altKey)&&b){if(this.ctx.lineWidth=u,e.shiftKey&&!e.altKey){s.dragFromLinkSegment(i,f),this.#l();return}else if(e.altKey&&!e.shiftKey){const v=i.createReroute([r,l],f);n.onDragStart=k=>this.#h(v,k),n.onDragEnd=k=>this.#g(k);return}}else if(this.linkMarkerShape!==re.None&&G(r,l,y[0]-4,y[1]-4,8,8)){this.ctx.lineWidth=u,n.onClick=()=>this.showLinkMenu(f,e),n.onDragStart=()=>this.dragging_canvas=!0,n.finally=()=>this.dragging_canvas=!1,this.over_link_center=void 0;return}}this.ctx.lineWidth=u;const g=i.getGroupOnPos(r,l);if(this.selected_group=g??null,g){if(g.isInResize(r,l)){const f=g.boundingRect,y=r-(f[0]+f[2]),b=l-(f[1]+f[3]);n.onDragStart=()=>this.resizingGroup=g,n.onDrag=v=>{if(this.read_only)return;const k=[v.canvasX-g.pos[0]-y,v.canvasY-g.pos[1]-b];this.#i&&xe(k,this.#i),g.resize(k[0],k[1])&&(this.dirty_bgcanvas=!0)},n.finally=()=>this.resizingGroup=null}else{const f=(g.font_size||_.DEFAULT_GROUP_FONT_SIZE)*1.4;G(r,l,g.pos[0],g.pos[1],g.size[0],f)&&(n.onClick=()=>this.processSelect(g,e),n.onDragStart=y=>{g.recomputeInsideNodes(),this.#h(g,y,!0)},n.onDragEnd=y=>this.#g(y))}n.onDoubleClick=()=>{this.emitEvent({subType:"group-double-click",originalEvent:e,group:g})}}else n.onDoubleClick=()=>{this.allow_searchbox&&(this.showSearchBox(e),e.preventDefault()),this.emitEvent({subType:"empty-double-click",originalEvent:e})}}!n.onDragStart&&!n.onClick&&!n.onDrag&&this.allow_dragcanvas&&(_.leftMouseClickBehavior==="panning"||this.read_only?(n.onClick=()=>this.processSelect(null,e),n.finally=()=>this.dragging_canvas=!1,this.dragging_canvas=!0):this.#p(e,n))}#p(e,t,n){const i=[0,0,0,0];if(i[0]=e.canvasX,i[1]=e.canvasY,i[2]=1,i[3]=1,t.onClick=s=>{const a=n??this.#u(s.canvasX,s.canvasY);this.processSelect(a,s)},t.onDragStart=()=>this.dragging_rectangle=i,this.liveSelection){const s=new Set(this.selectedItems);t.onDrag=a=>this.handleLiveSelect(a,i,s),t.onDragEnd=()=>this.finalizeLiveSelect()}else t.onDragEnd=s=>this.#C(s,i);t.finally=()=>this.dragging_rectangle=null}#m(e,t,n){if(_.vueNodesMode)return;const{pointer:i,graph:s,linkConnector:a}=this;if(!s)throw new N;const r=e.canvasX,l=e.canvasY;i.onClick=()=>this.processSelect(n,e),n.flags.pinned||this.bringToFront(n);const d=n.isPointInCollapse(r,l);if(d)i.onClick=()=>{n.collapse(),this.setDirty(!0,!0)};else if(!n.flags.collapsed){let f=function(y,b){return[...y.links??[],...y._floatingLinks??new Set].some(v=>typeof v=="number"&&b.getLink(v)!==void 0)};h(f,"hasRelevantOutputLinks");const{inputs:m,outputs:g}=n;if(g)for(const[y,b]of g.entries()){const v=n.getOutputPos(y);if(G(r,l,v[0]-15,v[1]-10,30,20)){if(e.shiftKey&&f(b,s)){a.moveOutputLink(s,b),this.#l();return}a.dragNewFromOutput(s,n,b),this.#l(),_.shift_click_do_break_link_from?e.shiftKey&&n.disconnectOutput(y):_.ctrl_alt_click_do_break_link&&t&&e.altKey&&!e.shiftKey&&n.disconnectOutput(y),i.onDoubleClick=()=>n.onOutputDblClick?.(y,e),i.onClick=()=>n.onOutputClick?.(y,e);return}}if(m)for(const[y,b]of m.entries()){const v=n.getInputPos(y);if(b instanceof Be?yt(r,l,b.boundingRect):G(r,l,v[0]-15,v[1]-10,30,20)){i.onDoubleClick=()=>n.onInputDblClick?.(y,e),i.onClick=()=>n.onInputClick?.(y,e);const k=_.ctrl_alt_click_do_break_link&&t&&e.altKey&&!e.shiftKey;(b.link!==null||b._floatingLinks?.size)&&(k||_.click_do_break_link_to?n.disconnectInput(y,!0):(e.shiftKey||this.allow_reconnect_links)&&a.moveInputLink(s,b)),a.isConnecting||a.dragNewFromInput(s,n,b),this.#l(),this.dirty_bgcanvas=!0;return}}}const u=[r-n.pos[0],l-n.pos[1]],p=n.getWidgetOnPos(r,l);if(p)this.processWidgetClick(e,n,p),this.node_widget=[n,p];else{if(i.onDoubleClick=()=>{u[1]<0&&!d?n.onNodeTitleDblClick?.(e,u,this):n instanceof gt&&this.openSubgraph(n.subgraph,n),n.onDblClick?.(e,u,this),this.emitEvent({subType:"node-double-click",originalEvent:e,node:n}),this.processNodeDblClicked(n)},n.title_buttons?.length&&!n.flags.collapsed){const m=u[0],g=u[1];for(let f=0;f<n.title_buttons.length;f++){const y=n.title_buttons[f];if(y.visible&&y.isPointInside(m,g)){n.onTitleButtonClick(y,this),i.onClick=()=>{};return}}}if(n.onMouseDown?.(e,u,this)){i.onClick=()=>{};return}if(!this.allow_dragnodes)return;if(!n.flags.collapsed){const m=n.findResizeDirection(r,l);if(m){i.resizeDirection=m;const g=new X(n.pos[0],n.pos[1],n.size[0],n.size[1]);i.onDragStart=()=>{s.beforeChange(),this.resizing_node=n},i.onDrag=f=>{if(this.read_only)return;const y=f.canvasX-r,b=f.canvasY-l,v=new X(g.x,g.y,g.width,g.height);switch(m){case"NE":v.y=g.y+b,v.width=g.width+y,v.height=g.height-b;break;case"SE":v.width=g.width+y,v.height=g.height+b;break;case"SW":v.x=g.x+y,v.width=g.width-y,v.height=g.height+b;break;case"NW":v.x=g.x+y,v.y=g.y+b,v.width=g.width-y,v.height=g.height-b;break}if(this.#i){if(m.includes("N")||m.includes("W")){const w=v.x,S=v.y;xe(v.pos,this.#i),m.includes("N")&&(v.height+=S-v.y),m.includes("W")&&(v.width+=w-v.x)}xe(v.size,this.#i)}const k=n.computeSize();v.width<k[0]&&(m.includes("W")&&(v.x=g.x+g.width-k[0]),v.width=k[0]),v.height<k[1]&&(m.includes("N")&&(v.y=g.y+g.height-k[1]),v.height=k[1]),n.pos=v.pos,n.setSize(v.size),this.#r()},i.onDragEnd=()=>{this.#r(),s.afterChange(n)},i.finally=()=>{this.resizing_node=null,i.resizeDirection=void 0},this.canvas.style.cursor=Gt[m];return}}i.onDragStart=m=>this.#h(n,m,!0),i.onDragEnd=m=>this.#g(m)}this.dirty_canvas=!0}processWidgetClick(e,t,n,i=this.pointer){if(typeof n.onPointerDown=="function"&&n.onPointerDown(i,t,this))return;const s=n.value,a=this.graph_mouse,r=a[0]-t.pos[0],l=a[1]-t.pos[1],d=Ct(n,t,!1);if(d)i.onClick=()=>d.onClick({e,node:t,canvas:this}),i.onDrag=u=>d.onDrag?.({e:u,node:t,canvas:this});else if(n.mouse){const u=n.mouse(e,[r,l],t);u!=null&&(this.dirty_canvas=u)}if(s!=n.value){if(t.onWidgetChanged?.(n.name,n.value,s,n),!t.graph)throw new N;t.graph._version++}i.finally=()=>{if(n.mouse){const{eUp:u}=i;if(!u)return;const{canvasX:p,canvasY:m}=u;n.mouse(u,[p-t.pos[0],m-t.pos[1]],t)}this.node_widget=null}}#_(e,t){const{pointer:n}=this;if(_.middle_click_slot_add_default_node&&t&&this.allow_interaction&&!this.read_only&&!this.connecting_links&&!t.flags.collapsed){let i=!1,s=!1,a=!1;const{inputs:r,outputs:l}=t;if(l)for(const[d,u]of l.entries()){const p=t.getOutputPos(d);if(G(e.canvasX,e.canvasY,p[0]-15,p[1]-10,30,20)){i=u,s=d,a=!0;break}}if(r)for(const[d,u]of r.entries()){const p=t.getInputPos(d);if(G(e.canvasX,e.canvasY,p[0]-15,p[1]-10,30,20)){i=u,s=d,a=!1;break}}if(i&&s!==!1){const d=.5-(s+1)/(a?l.length:r.length),u=t.getBounding(),p=[a?u[0]+u[2]:u[0],e.canvasY-80];n.onClick=()=>this.createDefaultNodeForSlot({nodeFrom:a?t:null,slotFrom:a?s:null,nodeTo:a?null:t,slotTo:a?null:s,position:p,nodeType:"AUTO",posAdd:[a?30:-30,-d*130],posSizeFix:[a?0:-1,0]})}}this.allow_dragcanvas&&(n.onDragStart=()=>this.dragging_canvas=!0,n.finally=()=>this.dragging_canvas=!1)}#v(e){if(!e.buttons){this.#b();return}const t=this.#a;if(!t)throw new TypeError("Drag-zoom state object was null");if(!this.graph)throw new N;const n=e.y-t.pos[1],i=t.scale-n/100;this.ds.changeScale(i,t.pos),this.graph.change()}#b(){const e=this.#a;e&&(this.#a=null,this.read_only=e.readOnly)}processMouseMove(e){if(this.dragZoomEnabled&&e.ctrlKey&&e.shiftKey&&this.#a){this.#v(e);return}this.autoresize&&this.resize(),this.set_canvas_dirty_on_mouse_event&&(this.dirty_canvas=!0);const{graph:t,resizingGroup:n,linkConnector:i,pointer:s,subgraph:a}=this;if(!t)return;L.active_canvas=this,this.adjustMouseEvent(e);const r=[e.clientX,e.clientY];this.mouse[0]=r[0],this.mouse[1]=r[1];const l=[r[0]-this.last_mouse[0],r[1]-this.last_mouse[1]];this.last_mouse=r;const{canvasX:d,canvasY:u}=e;this.graph_mouse[0]=d,this.graph_mouse[1]=u,e.isPrimary&&s.move(e);let p=te.Nothing;if(a&&(p|=a.inputNode.onPointerMove(e),p|=a.outputNode.onPointerMove(e)),this.block_click){e.preventDefault();return}if(e.dragging=this.last_mouse_dragging,this.node_widget){const[f,y]=this.node_widget;if(y?.mouse){const b=d-f.pos[0],v=u-f.pos[1],k=y.mouse(e,[b,v],f);k!=null&&(this.dirty_canvas=k)}}const m=_.vueNodesMode?null:t.getNodeOnPos(d,u,this.visible_nodes),g=this.dragging_rectangle;if(g)g[2]=d-g[0],g[3]=u-g[1],this.dirty_canvas=!0;else if(n)p|=te.Group,s.resizeDirection="SE";else if(this.dragging_canvas)this.ds.offset[0]+=l[0]/this.ds.scale,this.ds.offset[1]+=l[1]/this.ds.scale,this.#r();else if((this.allow_interaction||m?.flags.allow_interaction)&&!this.read_only){if(i.isConnecting&&(this.dirty_canvas=!0),this.updateMouseOverNodes(m,e),m){p|=te.Node,m.redraw_on_mouse&&(this.dirty_canvas=!0);const f=[0,0];let y=-1,b=-1;const v=D.querySlotAtPoint({x:d,y:u});v&&v.nodeId===String(m.id)?v.type==="input"?(y=v.index,f[0]=v.position.x,f[1]=v.position.y):(b=v.index,f[0]=v.position.x,f[1]=v.position.y):(y=vs(m,d,u,f),b=ks(m,d,u,f));const k=m.getWidgetOnPos(d,u,!0)??void 0;if(!m.mouseOver){m.mouseOver={},this.node_over=m,this.dirty_canvas=!0;for(const S of this.#s)S.hideSlots(),this.dirty_bgcanvas=!0;m.onMouseEnter?.(e)}m.onMouseMove?.(e,[d-m.pos[0],u-m.pos[1]],this);const{mouseOver:w}=m;if(w.inputId!==y||w.outputId!==b||w.overWidget!==k){if(w.inputId=y,w.outputId=b,w.overWidget=k,i.overWidget=void 0,i.isConnecting){const S=i.renderLinks.at(0);let E,C;if(!(!S||!i.isNodeValidDrop(m))){if(i.state.connectingTo==="input"){if(k){const I=m.getSlotFromWidget(k);if(I&&i.isInputValidDrop(m,I)){if(C=I,_.vueNodesMode){const P=m.inputs.indexOf(I);E=P!==-1?ae(m,P,!0):m.getInputSlotPos(I)}else E=m.getInputSlotPos(I);i.overWidget=k}}if(!i.overWidget){if(y===-1&&b===-1){const I=m.findInputByType(S.fromSlot.type);I&&(C=I.slot,E=_.vueNodesMode?ae(m,I.index,!0):m.getInputSlotPos(I.slot))}else y!=-1&&m.inputs[y]&&_.isValidConnection(S.fromSlot.type,m.inputs[y].type)&&(E=f,C=m.inputs[y]);if(C){const I=m.getWidgetFromSlot(C);I&&(i.overWidget=I)}}}else if(i.state.connectingTo==="output")if(y===-1&&b===-1){const I=m.findOutputByType(S.fromSlot.type);I&&(E=_.vueNodesMode?ae(m,I.index,!1):m.getOutputPos(I.index))}else b!=-1&&m.outputs[b]&&_.isValidConnection(S.fromSlot.type,m.outputs[b].type)&&(E=f)}this._highlight_pos=E,this._highlight_input=C}this.dirty_canvas=!0}s.eDown||(y===-1&&b===-1&&!k?s.resizeDirection=m.findResizeDirection(d,u):s.resizeDirection&&=void 0)}else{p=this.#S(p);const f=this.#T(e);if(this.over_link_center!==f&&(p|=te.Link,this.over_link_center=f,this.dirty_bgcanvas=!0),this.canvas){const y=t.getGroupOnPos(d,u);y&&!e.ctrlKey&&!this.read_only&&y.isInResize(d,u)?s.resizeDirection="SE":s.resizeDirection&&=void 0}}if(this.node_capturing_input&&this.node_capturing_input!=m&&this.node_capturing_input.onMouseMove?.(e,[d-this.node_capturing_input.pos[0],u-this.node_capturing_input.pos[1]],this),this.isDragging){const f=this.selectedItems,y=e.ctrlKey?f:yn(f),b=l[0]/this.ds.scale,v=l[1]/this.ds.scale;if(_.vueNodesMode)this.moveChildNodesInGroupVueMode(y,b,v);else for(const k of y)k.move(b,v,!0);this.#r()}}this.hoveringOver=p,e.preventDefault()}#S(e){const{graph:t,pointer:n,linkConnector:i}=this;if(!t)throw new N;if(n.isDown){if(i.isConnecting){for(const s of this.#s)if(s.containsPoint(this.graph_mouse))return i.isRerouteValidDrop(s)&&(i.overReroute=s,this._highlight_pos=s.pos),e|=te.RerouteSlot}}else{let s=!1;for(const a of this.#s)s||=a.updateVisibility(this.graph_mouse),a.isSlotHovered&&(e|=te.RerouteSlot);s&&(this.dirty_bgcanvas=!0)}return this._highlight_pos&&=void 0,i.overReroute&&=void 0,e}#h(e,t,n=!1){this.emitBeforeChange(),this.graph?.beforeChange(),t.finally=()=>{this.isDragging=!1,this.graph?.afterChange(),this.emitAfterChange()},this.processSelect(e,t.eDown,n),this.isDragging=!0}#g(e){const{graph:t}=this;(e.shiftKey||_.alwaysSnapToGrid)&&t?.snapToGrid(this.selectedItems),this.dirty_canvas=!0,this.dirty_bgcanvas=!0,this.onNodeMoved?.(Ts(this.selectedItems))}processMouseUp(e){if(e.isPrimary===!1)return;const{graph:t,pointer:n}=this;if(t){if(this.#b(),L.active_canvas=this,this.adjustMouseEvent(e),e.click_time=_.getTime()-this.last_mouseclick,n.up(e)===!0){n.isDown=!1,n.isDouble=!1,this.connecting_links=null,this.dragging_canvas=!1,t.change(),e.stopPropagation(),e.preventDefault();return}if(this.last_mouse_dragging=!1,this.last_click_position=null,this.block_click&&=!1,e.button===0){this.selected_group=null,this.isDragging=!1;const i=e.canvasX,s=e.canvasY;this.linkConnector.isConnecting||(this.dirty_canvas=!0,this.node_over?.onMouseUp?.(e,[i-this.node_over.pos[0],s-this.node_over.pos[1]],this),this.node_capturing_input?.onMouseUp?.(e,[i-this.node_capturing_input.pos[0],s-this.node_capturing_input.pos[1]],this))}else e.button===1?(this.dirty_canvas=!0,this.dragging_canvas=!1):e.button===2&&(this.dirty_canvas=!0);n.isDown=!1,n.isDouble=!1,t.change(),e.stopPropagation(),e.preventDefault()}}processMouseOut(e){this.adjustMouseEvent(e),this.updateMouseOverNodes(null,e)}processMouseCancel(){console.warn("Pointer cancel!"),this.pointer.reset()}processMouseWheel(e){if(!this.graph||!this.allow_dragcanvas)return;this.adjustMouseEvent(e);const t=[e.clientX,e.clientY];if(this.viewport&&!We(t,this.viewport))return;let{scale:n}=this.ds;const i=this.pointer.isTrackpadGesture(e);if((e.ctrlKey||e.metaKey&&navigator.platform.includes("Mac"))&&!e.altKey&&!e.shiftKey||_.mouseWheelScroll==="zoom")i?(n*=1+e.deltaY*(1-this.zoom_speed)*.18,this.ds.changeScale(n,[e.clientX,e.clientY],!1)):(e.deltaY<0?n*=this.zoom_speed:e.deltaY>0&&(n*=1/this.zoom_speed),this.ds.changeScale(n,[e.clientX,e.clientY]));else{const s=i?.18:.008333;!i&&e.shiftKey&&e.deltaX===0?this.ds.offset[0]-=e.deltaY*(1+s)*(1/n):(this.ds.offset[0]-=e.deltaX*(1+s)*(1/n),this.ds.offset[1]-=e.deltaY*(1+s)*(1/n))}this.graph.change(),e.preventDefault()}#I(){const e=new CustomEvent("litegraph:no-items-selected",{bubbles:!0});this.canvas.dispatchEvent(e)}processKey(e){this.#d=e.shiftKey;const{graph:t}=this;if(!t)return;let n=!1;if(e.target.localName!="input"){if(e.type=="keydown"){if(e.key===" ")this.read_only=!0,this._previously_dragging_canvas===null&&(this._previously_dragging_canvas=this.dragging_canvas),this.dragging_canvas=this.pointer.isDown,n=!0;else if(e.key==="Escape"){if(this.linkConnector.isConnecting){this.linkConnector.reset(),e.preventDefault();return}this.node_panel?.close(),this.options_panel?.close(),(this.node_panel||this.options_panel)&&(n=!0)}else if(e.keyCode===65&&e.ctrlKey)this.selectItems(),n=!0;else if(e.keyCode===67&&(e.metaKey||e.ctrlKey)&&!e.shiftKey)this.selected_nodes&&(this.copyToClipboard(),n=!0);else if(e.keyCode===86&&(e.metaKey||e.ctrlKey))this.pasteFromClipboard({connectInputs:e.shiftKey});else if((e.key==="Delete"||e.key==="Backspace")&&e.target.localName!="input"&&e.target.localName!="textarea"){if(this.selectedItems.size===0){this.#I();return}this.deleteSelected(),n=!0}for(const i of Object.values(this.selected_nodes))i.onKeyDown?.(e)}else if(e.type=="keyup"){e.key===" "&&(this.read_only=!1,this.dragging_canvas=(this._previously_dragging_canvas??!1)&&this.pointer.isDown,this._previously_dragging_canvas=null);for(const i of Object.values(this.selected_nodes))i.onKeyUp?.(e)}t.change(),n&&(e.preventDefault(),e.stopImmediatePropagation())}}_serializeItems(e){const t={nodes:[],groups:[],reroutes:[],links:[],subgraphs:[]},n=new Set;for(const i of e??this.selectedItems)if(i instanceof q){if(i.clonable===!1)continue;const s=i.clone()?.serialize();if(!s)continue;if(s.id=i.id,t.nodes.push(s),i.inputs)for(const{link:a}of i.inputs){if(a==null)continue;const r=this.graph?._links.get(a)?.asSerialisable();r&&t.links.push(r)}i instanceof gt&&n.add(i.subgraph)}else i instanceof de?t.groups.push(i.serialize()):i instanceof J&&t.reroutes.push(i.asSerialisable());for(const i of n){for(const a of i.nodes)a instanceof gt&&n.add(a.subgraph);const s=i.clone(!0).asSerialisable();t.subgraphs.push(s)}return t}copyToClipboard(e){const t=JSON.stringify(this._serializeItems(e));return localStorage.setItem("litegrapheditor_clipboard",t),t}emitEvent(e){this.canvas.dispatchEvent(new CustomEvent("litegraph:canvas",{bubbles:!0,detail:e}))}emitBeforeChange(){this.emitEvent({subType:"before-change"})}emitAfterChange(){this.emitEvent({subType:"after-change"})}_pasteFromClipboard(e={}){const t=localStorage.getItem("litegrapheditor_clipboard");if(t)return this._deserializeItems(JSON.parse(t),e)}_deserializeItems(e,t){const{connectInputs:n=!1,position:i=this.graph_mouse}=t;if(!_.ctrl_shift_v_paste_connect_unselected_outputs&&n)return;const{graph:s}=this;if(!s)throw new N;s.beforeChange(),this.emitBeforeChange(),e.nodes??=[],e.groups??=[],e.reroutes??=[],e.links??=[],e.subgraphs??=[];let a=1/0,r=1/0;for(const b of[...e.nodes,...e.reroutes]){if(b.pos==null)throw new TypeError("Invalid node encountered on paste. `pos` was null.");b.pos[0]<a&&(a=b.pos[0]),b.pos[1]<r&&(r=b.pos[1])}if(e.groups)for(const b of e.groups)b.bounding[0]<a&&(a=b.bounding[0]),b.bounding[1]<r&&(r=b.bounding[1]);const l={created:[],nodes:new Map,links:new Map,reroutes:new Map,subgraphs:new Map},{created:d,nodes:u,links:p,reroutes:m}=l,g={};for(const b of e.subgraphs)b.id=g[b.id]=fe();const f=[e.nodes?[e.nodes]:[],e.subgraphs?e.subgraphs.map(b=>b.nodes??[]):[]].flat(2);for(const b of f)b.type in g&&(b.type=g[b.type]);for(const b of e.subgraphs){const v=s.createSubgraph(b);l.subgraphs.set(b.id,v)}for(const b of e.subgraphs)l.subgraphs.get(b.id)?.configure(b);for(const b of e.groups){b.id=-1;const v=new de;v.configure(b),s.add(v),d.push(v)}for(const b of e.nodes){const v=b.type==null?null:_.createNode(b.type);v&&(u.set(b.id,v),b.id=-1,v.configure(b),s.add(v),d.push(v))}for(const b of e.reroutes){const{id:v,...k}=b,w=s.setReroute(k);d.push(w),m.set(v,w)}for(const b of m.values()){if(b.parentId==null)continue;const v=m.get(b.parentId);v&&(b.parentId=v.id)}for(const b of e.links){let v=u.get(b.origin_id),k;b.parentId!=null&&(k=m.get(b.parentId)?.id),n&&_.ctrl_shift_v_paste_connect_unselected_outputs&&(v??=s.getNodeById(b.origin_id),k??=b.parentId);const w=u.get(b.target_id);if(w){const S=v?.connect(b.origin_slot,w,b.target_slot,k);S&&p.set(b.id,S)}}for(const b of m.values()){const v=[...b.linkIds].map(k=>p.get(k)?.id??k);b.update(b.parentId,void 0,v,b.floating),b.validateLinks(s.links,s.floatingLinks)||s.removeReroute(b.id)}for(const b of d)b.pos[0]+=i[0]-a,b.pos[1]+=i[1]-r;const y=d.filter(b=>b instanceof q).map(b=>{const v=b.size?.[1]??200,k=_.vueNodesMode?on(v):v;return{nodeId:String(b.id),bounds:{x:b.pos[0],y:b.pos[1],width:b.size?.[0]??100,height:k}}});return y.length&&D.setSource(ue.Canvas),D.batchUpdateNodeBounds(y),this.selectItems(d),Ge(s,b=>b.onGraphConfigured?.()),Ge(s,b=>b.onAfterGraphConfigured?.()),s.afterChange(),this.emitAfterChange(),l}pasteFromClipboard(e={}){this.emitBeforeChange();try{this._pasteFromClipboard(e)}finally{this.emitAfterChange()}}processNodeDblClicked(e){this.onShowNodePanel?.(e),this.onNodeDblClicked?.(e),this.setDirty(!0)}#k(e){const t=Math.abs(e[2]),n=Math.abs(e[3]);return e[2]<0&&(e[0]-=t),e[3]<0&&(e[1]-=n),e[2]=t,e[3]=n,e}#w(e){const{graph:t,subgraph:n}=this;if(!t)throw new N;const i=new Set;if(n){const{inputNode:s,outputNode:a}=n;Le(e,s.boundingRect)&&i.add(s),Le(e,a.boundingRect)&&i.add(a)}for(const s of t._nodes)Le(e,s.boundingRect)&&i.add(s);for(const s of t.groups)en(e,s._bounding)&&(s.recomputeInsideNodes(),i.add(s));for(const s of t.reroutes.values())We(s.pos,e)&&i.add(s);return i}handleLiveSelect(e,t,n){t[2]=e.canvasX-t[0],t[3]=e.canvasY-t[1];const i=[t[0],t[1],t[2],t[3]];this.#k(i);const s=this.#w(i),a=new Set;if(e.shiftKey&&!e.altKey){for(const l of n)a.add(l);for(const l of s)a.add(l)}else if(e.altKey&&!e.shiftKey)for(const l of n)s.has(l)||a.add(l);else for(const l of s)a.add(l);let r=!1;for(const l of[...this.selectedItems])a.has(l)||(this.deselect(l),r=!0);for(const l of a)this.selectedItems.has(l)||(this.select(l),r=!0);r&&(this.onSelectionChange?.(this.selected_nodes),this.setDirty(!0))}finalizeLiveSelect(){this.onSelectionChange?.(this.selected_nodes)}#C(e,t){const n=[t[0],t[1],t[2],t[3]];this.#k(n);const i=this.#w(n),{selectedItems:s}=this;if(e.shiftKey)for(const a of i)this.select(a);else if(e.altKey)for(const a of i)this.deselect(a);else{for(const a of s.values())i.has(a)||this.deselect(a);for(const a of i)this.select(a)}this.onSelectionChange?.(this.selected_nodes)}processSelect(e,t,n=!1){const i=t?.shiftKey,s=t!=null&&(t.metaKey||t.ctrlKey),a=i||s,r=a||this.multi_select;if(!e)(!a||this.multi_select)&&this.deselectAll();else if(!e.selected||!this.selectedItems.has(e))r||this.deselectAll(e),this.select(e);else if(r&&!n)this.deselect(e);else if(!n)this.deselectAll(e);else return;this.onSelectionChange?.(this.selected_nodes),this.setDirty(!0)}select(e){if(!(e.selected&&this.selectedItems.has(e))&&(e.selected=!0,this.selectedItems.add(e),this.state.selectionChanged=!0,e instanceof q)){if(e.onSelected?.(),this.selected_nodes[e.id]=e,this.onNodeSelected?.(e),e.inputs)for(const t of e.inputs)t.link!=null&&(this.highlighted_links[t.link]=!0);if(e.outputs)for(const t of e.outputs.flatMap(n=>n.links))t!=null&&(this.highlighted_links[t]=!0)}}deselect(e){if(!e.selected&&!this.selectedItems.has(e)||(e.selected=!1,this.selectedItems.delete(e),this.state.selectionChanged=!0,!(e instanceof q)))return;e.onDeselected?.(),delete this.selected_nodes[e.id],this.onNodeDeselected?.(e);const{graph:t}=this;if(t){if(e.inputs)for(const n of e.inputs){if(n.link==null)continue;const i=z.getOriginNode(t,n.link);i&&this.selectedItems.has(i)||delete this.highlighted_links[n.link]}if(e.outputs)for(const n of e.outputs.flatMap(i=>i.links)){if(n==null)continue;const i=z.getTargetNode(t,n);i&&this.selectedItems.has(i)||delete this.highlighted_links[n]}}}processNodeSelected(e,t){this.processSelect(e,t,t&&(t.shiftKey||t.metaKey||t.ctrlKey||this.multi_select))}selectNode(e,t){e==null?this.deselectAll():this.selectNodes([e],t)}get empty(){if(!this.graph)throw new N;return this.graph.empty}get positionableItems(){if(!this.graph)throw new N;return this.graph.positionableItems()}selectItems(e,t){const n=e??this.positionableItems;t||this.deselectAll();for(const i of n)this.select(i);this.onSelectionChange?.(this.selected_nodes),this.setDirty(!0)}selectNodes(e,t){this.selectItems(e,t)}deselectNode(e){this.deselect(e)}deselectAll(e){if(!this.graph)return;const t=this.selectedItems;if(!t.size)return;const n=t.size;let i;for(const a of t){if(a===e){i=a;continue}a.onDeselected?.(),a.selected=!1}t.clear(),i&&t.add(i),this.setDirty(!0);const s=e?.id==null?null:this.selected_nodes[e.id];if(this.selected_nodes={},this.current_node=null,this.highlighted_links={},e instanceof q){if(s&&(this.selected_nodes[s.id]=s),e.inputs)for(const a of e.inputs)a.link!=null&&(this.highlighted_links[a.link]=!0);if(e.outputs)for(const a of e.outputs.flatMap(r=>r.links))a!=null&&(this.highlighted_links[a]=!0)}n!==t.size&&(this.state.selectionChanged=!0,this.onSelectionChange?.(this.selected_nodes))}deselectAllNodes(){this.deselectAll()}deleteSelected(){const{graph:e}=this;if(!e)throw new N;this.emitBeforeChange(),e.beforeChange();for(const t of this.selectedItems)if(t instanceof q){const n=t;if(n.block_delete)continue;n.connectInputToOutput(),e.remove(n),this.onNodeDeselected?.(n)}else t instanceof de?e.remove(t):t instanceof J&&e.removeReroute(t.id);this.selected_nodes={},this.selectedItems.clear(),this.current_node=null,this.highlighted_links={},this.state.selectionChanged=!0,this.onSelectionChange?.(this.selected_nodes),this.setDirty(!0),e.afterChange(),this.emitAfterChange()}deleteSelectedNodes(){this.deleteSelected()}centerOnNode(e){const t=window?.devicePixelRatio||1;this.ds.offset[0]=-e.pos[0]-e.size[0]*.5+this.canvas.width*.5/(this.ds.scale*t),this.ds.offset[1]=-e.pos[1]-e.size[1]*.5+this.canvas.height*.5/(this.ds.scale*t),this.setDirty(!0,!0)}adjustMouseEvent(e){let t=e.clientX,n=e.clientY;if(this.canvas){const i=this.canvas.getBoundingClientRect();t-=i.left,n-=i.top}e.safeOffsetX=t,e.safeOffsetY=n,e.deltaX===void 0&&(e.deltaX=t-this.last_mouse_position[0]),e.deltaY===void 0&&(e.deltaY=n-this.last_mouse_position[1]),this.last_mouse_position[0]=t,this.last_mouse_position[1]=n,e.canvasX=t/this.ds.scale-this.ds.offset[0],e.canvasY=n/this.ds.scale-this.ds.offset[1]}setZoom(e,t){this.ds.changeScale(e,t),this.#r()}convertOffsetToCanvas(e,t){return this.ds.convertOffsetToCanvas(e)}convertCanvasToOffset(e,t){return this.ds.convertCanvasToOffset(e,t)}convertEventToCanvasOffset(e){const t=this.canvas.getBoundingClientRect();return this.convertCanvasToOffset([e.clientX-t.left,e.clientY-t.top])}bringToFront(e){const{graph:t}=this;if(!t)throw new N;const n=t._nodes.indexOf(e);n!=-1&&(t._nodes.splice(n,1),t._nodes.push(e))}sendToBack(e){const{graph:t}=this;if(!t)throw new N;const n=t._nodes.indexOf(e);n!=-1&&(t._nodes.splice(n,1),t._nodes.unshift(e))}computeVisibleNodes(e,t){const n=t||[];if(n.length=0,!this.graph)throw new N;const i=e||this.graph._nodes;for(const s of i)s.updateArea(this.ctx),Le(this.visible_area,s.renderArea)&&n.push(s);return n}isNodeVisible(e){return this.#n.has(e.id)}draw(e,t){if(!this.canvas||this.canvas.width==0||this.canvas.height==0)return;const n=_.getTime();if(this.render_time=(n-this.last_draw_time)*.001,this.last_draw_time=n,this.graph&&this.ds.computeVisibleArea(this.viewport),this.dirty_canvas||e){this.computeVisibleNodes(void 0,this.visible_nodes),this.#n=new Set(this.visible_nodes.map(s=>s.id));const{subgraph:i}=this;i&&(i.inputNode.arrange(),i.outputNode.arrange())}(this.dirty_bgcanvas||t||this.always_render_background||this.graph?._last_trigger_time&&n-this.graph._last_trigger_time<1e3)&&this.drawBackCanvas(),(this.dirty_canvas||e)&&this.drawFrontCanvas(),this.fps=this.render_time?1/this.render_time:0,this.frame++}drawFrontCanvas(){this.dirty_canvas=!1;const{ctx:e,canvas:t,graph:n,linkConnector:i}=this;e.start2D&&!this.viewport&&(e.start2D(),e.restore(),e.setTransform(1,0,0,1,0,0));const s=this.viewport||this.dirty_area;if(s&&(e.save(),e.beginPath(),e.rect(s[0],s[1],s[2],s[3]),e.clip()),this.#i=this.#d||_.alwaysSnapToGrid?this.graph?.getSnapToGridSize():void 0,this.clear_background&&(s?e.clearRect(s[0],s[1],s[2],s[3]):e.clearRect(0,0,t.width,t.height)),this.bgcanvas==this.canvas)this.drawBackCanvas();else{const a=window.devicePixelRatio;e.drawImage(this.bgcanvas,0,0,this.bgcanvas.width/a,this.bgcanvas.height/a)}if(this.onRender?.(t,e),this.show_info){const a=this.fpsInfoLocation??s;this.renderInfo(e,a?.[0]??0,a?.[1]??0)}if(n){e.save(),this.ds.toCanvasContext(e);const{visible_nodes:a}=this,r=this.#i&&(this.isDragging||D.isDraggingVueNodes.value);for(const l of a)e.save(),r&&this.selectedItems.has(l)&&this.drawSnapGuide(e,l),e.translate(l.pos[0],l.pos[1]),this.drawNode(l,e),e.restore();if(this.subgraph?.draw(e,this.colourGetter,this.linkConnector.renderLinks[0]?.fromSlot,this.editor_alpha),this.render_execution_order&&this.drawExecutionOrder(e),n.config.links_ontop&&this.drawConnections(e),i.isConnecting){const{renderLinks:l}=i,d=this.#L();e.lineWidth=this.connections_width;for(const u of l){const{fromSlot:p,fromPos:m,fromDirection:g,dragDirection:f}=u,y=p.shape,b=p.type,v=Fw(b);this.linkRenderer&&this.linkRenderer.renderDraggingLink(e,m,d,v,g,f,{...this.buildLinkRenderContext(),linkMarkerShape:re.None}),e.fillStyle=v,e.beginPath(),b===_.EVENT||y===M.BOX?(e.rect(m[0]-6+.5,m[1]-5+.5,14,10),e.rect(d[0]-6+.5,d[1]-5+.5,14,10)):y===M.ARROW?(e.moveTo(m[0]+8,m[1]+.5),e.lineTo(m[0]-4,m[1]+6+.5),e.lineTo(m[0]-4,m[1]-6+.5),e.closePath()):(e.arc(m[0],m[1],4,0,Math.PI*2),e.arc(d[0],d[1],4,0,Math.PI*2)),e.fill()}this.#E(e,d)}!this.isDragging&&this.over_link_center&&this.render_link_tooltip?this.drawLinkTooltip(e,this.over_link_center):this.onDrawLinkTooltip?.(e,null),this.onDrawForeground?.(e,this.visible_area),e.restore()}this.onDrawOverlay?.(e),s&&e.restore()}#T(e){if(this.linkMarkerShape!==re.None)for(const t of this.renderedPaths){const n=t._pos;if(n&&G(e.canvasX,e.canvasY,n[0]-4,n[1]-4,8,8))return t}}#L(){return _.snaps_for_comfy?this.linkConnector.state.snapLinksPos??this._highlight_pos??this.graph_mouse:this.graph_mouse}#E(e,t){const n=!!this.linkConnector.state.snapLinksPos;if(!this._highlight_pos&&!n)return;e.fillStyle="#ffcc00",e.beginPath(),this._highlight_input?.shape===M.ARROW?(e.moveTo(t[0]+8,t[1]+.5),e.lineTo(t[0]-4,t[1]+6+.5),e.lineTo(t[0]-4,t[1]-6+.5),e.closePath()):e.arc(t[0],t[1],6,0,Math.PI*2),e.fill();const{linkConnector:i}=this,{overReroute:s,overWidget:a}=i;if(!_.snap_highlights_node||!i.isConnecting||n)return;s?.drawHighlight(e,"#ffcc00aa");const r=this.node_over;if(!r)return;const{strokeStyle:l,lineWidth:d}=e,u=r.boundingRect,p=3,m=_.ROUND_RADIUS+p,g=u[0]-p,f=u[1]-p,y=u[2]+p*2,b=u[3]+p*2;e.beginPath(),e.roundRect(g,f,y,b,m);const v=i.state.connectingTo==="output"?0:1,k=v?-1:1,w=t[0],S=t[1],E=y<b?y:y*Math.max(b/y,.5),C=e.createRadialGradient(w,S,0,w,S,E);C.addColorStop(1,"#00000000"),C.addColorStop(0,"#ffcc00aa");const I=e.createLinearGradient(g,f,g+y,f);if(I.addColorStop(.5,"#00000000"),I.addColorStop(v+.67*k,"#ddeeff33"),I.addColorStop(v+k,"#ffcc0055"),e.setLineDash([m,m*.001]),e.lineWidth=1,e.strokeStyle=I,e.stroke(),a){const{computedHeight:P}=a;e.beginPath();const{pos:[A,F]}=r,T=_.NODE_WIDGET_HEIGHT;a.type.startsWith("custom")&&P!=null&&P>T*2?e.rect(A+9,F+a.y+9,(a.width??u[2])-18,P-18):e.roundRect(A+B.margin,F+a.y,a.width??u[2],T,T*.5),e.stroke()}e.strokeStyle=C,e.stroke(),e.setLineDash([]),e.lineWidth=d,e.strokeStyle=l}renderInfo(e,t,n){t=t||10,n=n||this.canvas.offsetHeight-80,e.save(),e.translate(t,n),e.font=`10px ${_.DEFAULT_FONT}`,e.fillStyle="#888",e.textAlign="left",this.graph?(e.fillText(`T: ${this.graph.globaltime.toFixed(2)}s`,5,13),e.fillText(`I: ${this.graph.iteration}`,5,26),e.fillText(`N: ${this.graph._nodes.length} [${this.visible_nodes.length}]`,5,39),e.fillText(`V: ${this.graph._version}`,5,52),e.fillText(`FPS:${this.fps.toFixed(2)}`,5,65)):e.fillText("No graph selected",5,13),e.restore()}drawBackCanvas(){const e=this.bgcanvas;(e.width!=this.canvas.width||e.height!=this.canvas.height)&&(e.width=this.canvas.width,e.height=this.canvas.height),this.bgctx||(this.bgctx=this.bgcanvas.getContext("2d"));const t=this.bgctx;if(!t)throw new TypeError("Background canvas context was null.");const n=this.viewport||[0,0,t.canvas.width,t.canvas.height];this.clear_background&&t.clearRect(n[0],n[1],n[2],n[3]);const i=this.onRenderBackground?this.onRenderBackground(e,t):!1;if(!this.viewport){const s=window.devicePixelRatio;t.restore(),t.setTransform(s,0,0,s,0,0)}if(this.graph){if(t.save(),this.ds.toCanvasContext(t),this.ds.scale<1.5&&!i&&this.clear_background_color&&(t.fillStyle=this.clear_background_color,t.fillRect(this.visible_area[0],this.visible_area[1],this.visible_area[2],this.visible_area[3])),this.background_image&&this.ds.scale>.5&&!i){this.zoom_modify_alpha?t.globalAlpha=(1-.5/this.ds.scale)*this.editor_alpha:t.globalAlpha=this.editor_alpha,t.imageSmoothingEnabled=!1,(!this._bg_img||this._bg_img.name!=this.background_image)&&(this._bg_img=new Image,this._bg_img.name=this.background_image,this._bg_img.src=this.background_image,this._bg_img.addEventListener("load",()=>{this.draw(!0,!0)}));let s=this._pattern;s==null&&this._bg_img.width>0&&(s=t.createPattern(this._bg_img,"repeat")??void 0,this._pattern_img=this._bg_img,this._pattern=s),s&&(t.fillStyle=s,t.fillRect(this.visible_area[0],this.visible_area[1],this.visible_area[2],this.visible_area[3]),t.fillStyle="transparent"),t.globalAlpha=1,t.imageSmoothingEnabled=!0}this.bg_tint&&(t.fillStyle=this.bg_tint,t.fillRect(this.visible_area[0],this.visible_area[1],this.visible_area[2],this.visible_area[3]),t.fillStyle="transparent"),this.graph._groups.length&&this.drawGroups(e,t),this.onDrawBackground?.(t,this.visible_area),this.render_canvas_border&&(t.strokeStyle="#235",t.strokeRect(0,0,e.width,e.height)),this.render_connections_shadows?(t.shadowColor="#000",t.shadowOffsetX=0,t.shadowOffsetY=0,t.shadowBlur=6):t.shadowColor="rgba(0,0,0,0)",this.drawConnections(t),t.shadowColor="rgba(0,0,0,0)",t.restore()}this.dirty_bgcanvas=!1,this.dirty_canvas=!0}drawNode(e,t){if(this.current_node=e,_.vueNodesMode){e._setConcreteSlots(),e.collapsed||e.arrange();return}const n=e.renderingColor,i=e.renderingBgColor;if(t.globalAlpha=this.getNodeModeAlpha(e),this.render_shadows&&!this.low_quality?(t.shadowColor=_.DEFAULT_SHADOW_COLOR,t.shadowOffsetX=2*this.ds.scale,t.shadowOffsetY=2*this.ds.scale,t.shadowBlur=3*this.ds.scale):t.shadowColor="transparent",e.flags.collapsed&&e.onDrawCollapsed?.(t,this)==!0)return;const s=e._shape||M.BOX,a=Bw;if(a[0]=e.renderingSize[0],a[1]=e.renderingSize[1],e.collapsed&&(t.font=this.inner_text_font),e.clip_area&&(t.save(),t.beginPath(),s==M.BOX?t.rect(0,0,a[0],a[1]):s==M.ROUND?t.roundRect(0,0,a[0],a[1],[10]):s==M.CIRCLE&&t.arc(a[0]*.5,a[1]*.5,a[0]*.5,0,Math.PI*2),t.clip()),this.drawNodeShape(e,t,a,n,i,!!e.selected),e.title_buttons&&!e.flags.collapsed){const r=_.NODE_TITLE_HEIGHT;let l=a[0];for(let d=0;d<e.title_buttons.length;d++){const u=e.title_buttons[d];if(!u.visible)continue;const p=u.getWidth(t);l-=p;const m=-r+(r-u.height)/2;u.draw(t,l,m),l-=2}}this.low_quality||e.drawBadges(t),t.shadowColor="transparent",t.strokeStyle=_.NODE_BOX_OUTLINE_COLOR,e.onDrawForeground?.(t,this,this.canvas),t.font=this.inner_text_font,e._setConcreteSlots(),e.collapsed?this.render_collapsed_slots&&e.drawCollapsedSlots(t):(e.arrange(),e.drawSlots(t,{fromSlot:this.linkConnector.renderLinks[0]?.fromSlot,colorContext:this.colourGetter,editorAlpha:this.editor_alpha,lowQuality:this.low_quality}),t.textAlign="left",t.globalAlpha=1,this.drawNodeWidgets(e,null,t)),e.clip_area&&t.restore(),t.globalAlpha=1}drawLinkTooltip(e,t){const n=t._pos;if(e.fillStyle="black",e.beginPath(),this.linkMarkerShape===re.Arrow){const l=e.getTransform();e.translate(n[0],n[1]),Number.isFinite(t._centreAngle)&&e.rotate(t._centreAngle),e.moveTo(-2,-3),e.lineTo(4,0),e.lineTo(-2,3),e.setTransform(l)}else(this.linkMarkerShape==null||this.linkMarkerShape===re.Circle)&&e.arc(n[0],n[1],3,0,Math.PI*2);e.fill();const{data:i}=t;if(i==null||this.onDrawLinkTooltip?.(e,t,this)==!0)return;let s=null;if(typeof i=="number"?s=i.toFixed(2):typeof i=="string"?s=`"${i}"`:typeof i=="boolean"?s=String(i):i.toToolTip?s=i.toToolTip():s=`[${i.constructor.name}]`,s==null)return;s=s.substring(0,30),e.font="14px Courier New";const a=e.measureText(s).width+20,r=24;e.shadowColor="black",e.shadowOffsetX=2,e.shadowOffsetY=2,e.shadowBlur=3,e.fillStyle="#454",e.beginPath(),e.roundRect(n[0]-a*.5,n[1]-15-r,a,r,[3]),e.moveTo(n[0]-10,n[1]-15),e.lineTo(n[0]+10,n[1]-15),e.lineTo(n[0],n[1]-5),e.fill(),e.shadowColor="transparent",e.textAlign="center",e.fillStyle="#CEC",e.fillText(s,n[0],n[1]-15-r*.3)}drawNodeShape(e,t,n,i,s,a){t.strokeStyle=i,t.fillStyle=s;const r=_.NODE_TITLE_HEIGHT,{low_quality:l}=this,{collapsed:d}=e.flags,u=e.renderingShape,{title_mode:p}=e,m=!(p==se.TRANSPARENT_TITLE||p==se.NO_TITLE),g=Vw;g.set(e.boundingRect),g[0]-=e.pos[0],g[1]-=e.pos[1];const f=t.globalAlpha;t.beginPath(),u==M.BOX||l?t.rect(g[0],g[1],g[2],g[3]):u==M.ROUND||u==M.CARD?t.roundRect(g[0],g[1],g[2],g[3],u==M.CARD?[_.ROUND_RADIUS,_.ROUND_RADIUS,0,0]:[_.ROUND_RADIUS]):u==M.CIRCLE&&t.arc(n[0]*.5,n[1]*.5,n[0]*.5,0,Math.PI*2),t.fill(),!d&&m&&(t.shadowColor="transparent",t.fillStyle="rgba(0,0,0,0.2)",t.fillRect(0,-1,g[2],2)),t.shadowColor="transparent",e.onDrawBackground?.(t),(m||p==se.TRANSPARENT_TITLE)&&(e.drawTitleBarBackground(t,{scale:this.ds.scale,low_quality:l}),e.drawTitleBox(t,{scale:this.ds.scale,low_quality:l,box_size:10}),t.globalAlpha=f,e.drawTitleText(t,{scale:this.ds.scale,default_title_color:this.node_title_color,low_quality:l}),e.onDrawTitle?.(t));for(const y of Object.values(e.strokeStyles)){const b=y.call(e);b&&gn(t,g,{shape:u,title_height:r,title_mode:p,collapsed:d,...b})}e.drawProgressBar(t),e.execute_triggered!=null&&e.execute_triggered>0&&e.execute_triggered--,e.action_triggered!=null&&e.action_triggered>0&&e.action_triggered--}drawSnapGuide(e,t,n=M.ROUND){const i=zw;i.set(t.boundingRect);const{pos:s}=t,a=s[0]-i[0],r=s[1]-i[1];i[0]+=a,i[1]+=r,this.#i&&xe(i,this.#i),i[0]-=a,i[1]-=r;const{globalAlpha:l}=e;e.globalAlpha=1,e.beginPath();const[d,u,p,m]=i;if(n===M.CIRCLE){const g=d+p*.5,f=u+m*.5,y=Math.min(p*.5,m*.5);e.arc(g,f,y,0,Math.PI*2)}else e.rect(d,u,p,m);e.lineWidth=.5,e.strokeStyle="#FFFFFF66",e.fillStyle="#FFFFFF22",e.fill(),e.stroke(),e.globalAlpha=l}drawConnections(e){if(this.renderedPaths.clear(),this.links_render_mode===ie.HIDDEN_LINK)return;const{graph:t,subgraph:n}=this;if(!t)throw new N;const i=[],s=_.getTime(),{visible_area:a}=this;$e[0]=a[0]-20,$e[1]=a[1]-20,$e[2]=a[2]+40,$e[3]=a[3]+40,e.lineWidth=this.connections_width,e.fillStyle="#AAA",e.strokeStyle="#AAA",e.globalAlpha=this.editor_alpha;const r=t._nodes;for(const d of r){const{inputs:u}=d;if(u?.length)for(const[p,m]of u.entries()){if(!m||m.link==null)continue;const g=m.link,f=t._links.get(g);if(!f)continue;const y=_.vueNodesMode?ae(d,p,!0):d.getInputPos(p),b=t.getNodeById(f.origin_id);if(b==null)continue;const v=f.origin_slot,k=v===-1?[b.pos[0]+10,b.pos[1]+10]:_.vueNodesMode?ae(b,v,!1):b.getOutputPos(v),w=b.outputs[v];w&&this.#y(e,f,k,y,i,s,w.dir,m.dir)}}if(n){for(const d of n.inputNode.slots)if(d.linkIds.length)for(const u of d.linkIds){const p=z.resolve(u,t);if(!p)continue;const{link:m,inputNode:g,input:f}=p;if(!g||!f)continue;const y=_.vueNodesMode?ae(g,m.target_slot,!0):g.getInputPos(m.target_slot);this.#y(e,m,d.pos,y,i,s,f.dir,f.dir)}for(const d of n.outputNode.slots){if(!d.linkIds.length)continue;const u=z.resolve(d.linkIds[0],t);if(!u)continue;const{link:p,outputNode:m,output:g}=u;if(!m||!g)continue;const f=_.vueNodesMode?ae(m,p.origin_slot,!1):m.getOutputPos(p.origin_slot);this.#y(e,p,f,d.pos,i,s,g.dir,d.dir)}}t.floatingLinks.size>0&&this.#N(e,t,i,s);const l=this.#s;l.clear(),i.sort((d,u)=>d.linkIds.size-u.linkIds.size);for(const d of i)l.add(d),this.#i&&this.isDragging&&this.selectedItems.has(d)&&this.drawSnapGuide(e,d,M.CIRCLE),d.draw(e,this._pattern),this.pointer.isDown||d.drawSlots(e);e.globalAlpha=1}getNodeModeAlpha(e){return e.mode===H.BYPASS?.2:e.mode===H.NEVER?.4:this.editor_alpha}#N(e,t,n,i){const{globalAlpha:s}=e;e.globalAlpha=s*.33;for(const a of t.floatingLinks.values()){const r=z.getReroutes(t,a),l=r[0],d=r.at(-1);if(!(!l||!d?.floating))if(d.floating.slotType==="input"){const u=t.getNodeById(a.target_id);if(!u)continue;const p=l.pos,m=_.vueNodesMode?ae(u,a.target_slot,!0):u.getInputPos(a.target_slot),g=u.inputs[a.target_slot]?.dir;l._dragging=!0,this.#y(e,a,p,m,n,i,O.CENTER,g,!0)}else{const u=t.getNodeById(a.origin_id);if(!u)continue;const p=_.vueNodesMode?ae(u,a.origin_slot,!1):u.getOutputPos(a.origin_slot),m=d.pos,g=u.outputs[a.origin_slot]?.dir;a._dragging=!0,this.#y(e,a,p,m,n,i,g,O.CENTER,!0)}}e.globalAlpha=s}#y(e,t,n,i,s,a,r,l,d=!1){const{graph:u,renderedPaths:p}=this;if(!u)return;const m=z.getReroutes(u,t),g=[n,...m.map(k=>k.pos),i],f=g.map(k=>k[0]),y=g.map(k=>k[1]);if(Te[0]=Math.min(...f),Te[1]=Math.min(...y),Te[2]=Math.max(...f)-Te[0],Te[3]=Math.max(...y)-Te[1],!Le(Te,$e))return;const b=r||O.RIGHT,v=l||O.LEFT;if(m.length){let k;const w=m.length;for(let E=0;E<w;E++){const C=m[E];if(!p.has(C)){p.add(C),s.push(C),C._colour=t.color||L.link_type_colors[t.type]||this.default_link_color;const I=u.getReroute(C.parentId)?.pos??n;C.calculateAngle(this.last_draw_time,u,I),C._dragging||this.renderLink(e,I,C.pos,t,!1,0,null,k===void 0?b:O.CENTER,O.CENTER,{startControl:k,endControl:C.controlPoint,reroute:C,disabled:d})}if(!k&&m.at(-1)?.floating?.slotType==="input")k=[0,0];else{const I=m[E+1]?.pos??i,P=Math.min(J.maxSplineOffset,Ue(C.pos,I)*.25);k=[P*C.cos,P*C.sin]}}if(t._dragging)return;const S=g.at(-2)??n;this.renderLink(e,S,i,t,!1,0,null,O.CENTER,v,{startControl:k,disabled:d})}else t._dragging||this.renderLink(e,n,i,t,!1,0,null,b,v);if(p.add(t),t?._last_time&&a-t._last_time<1e3){const k=2-(a-t._last_time)*.002,w=e.globalAlpha;e.globalAlpha=w*k,this.renderLink(e,n,i,t,!0,k,"white",b,v),e.globalAlpha=w}}buildLinkRenderContext(){return{renderMode:this.links_render_mode,connectionWidth:this.connections_width,renderBorder:this.render_connections_border,lowQuality:this.low_quality,highQualityRender:this.highquality_render,scale:this.ds.scale,linkMarkerShape:this.linkMarkerShape,renderConnectionArrows:this.render_connection_arrows,highlightedLinks:new Set(Object.keys(this.highlighted_links)),defaultLinkColor:this.default_link_color,linkTypeColors:L.link_type_colors,disabledPattern:this._pattern}}renderLink(e,t,n,i,s,a,r,l,d,{startControl:u,endControl:p,reroute:m,num_sublines:g=1,disabled:f=!1}={}){if(this.linkRenderer){const y=this.buildLinkRenderContext();this.linkRenderer.renderLinkDirect(e,t,n,i,s,a,r,l,d,y,{reroute:m,startControl:u,endControl:p,num_sublines:g,disabled:f})}}drawExecutionOrder(e){e.shadowColor="transparent",e.globalAlpha=.25,e.textAlign="center",e.strokeStyle="white",e.globalAlpha=.75;const{visible_nodes:t}=this;for(const n of t)e.fillStyle="black",e.fillRect(n.pos[0]-_.NODE_TITLE_HEIGHT,n.pos[1]-_.NODE_TITLE_HEIGHT,_.NODE_TITLE_HEIGHT,_.NODE_TITLE_HEIGHT),n.order==0&&e.strokeRect(n.pos[0]-_.NODE_TITLE_HEIGHT+.5,n.pos[1]-_.NODE_TITLE_HEIGHT+.5,_.NODE_TITLE_HEIGHT,_.NODE_TITLE_HEIGHT),e.fillStyle="#FFF",e.fillText($t(n.order),n.pos[0]+_.NODE_TITLE_HEIGHT*-.5,n.pos[1]-6);e.globalAlpha=1}drawNodeWidgets(e,t,n){e.drawWidgets(n,{lowQuality:this.low_quality,editorAlpha:this.getNodeModeAlpha(e)})}drawGroups(e,t){if(!this.graph)return;const n=this.graph._groups;t.save(),t.globalAlpha=.5*this.editor_alpha;const i=this.#i&&(this.isDragging||D.isDraggingVueNodes.value);for(const s of n)Le(this.visible_area,s._bounding)&&(i&&this.selectedItems.has(s)&&this.drawSnapGuide(t,s),s.draw(this,t));t.restore()}resize(e,t){if(!e&&!t){const n=this.canvas.parentElement;if(!n)throw new TypeError("Attempted to resize canvas, but parent element was null.");e=n.offsetWidth,t=n.offsetHeight}this.canvas.width==e&&this.canvas.height==t||(this.canvas.width=e??0,this.canvas.height=t??0,this.bgcanvas.width=this.canvas.width,this.bgcanvas.height=this.canvas.height,this.setDirty(!0,!0))}onNodeSelectionChange(){}boundaryNodesForSelection(){return L.getBoundaryNodes(this.selected_nodes)}showLinkMenu(e,t){const{graph:n}=this;if(!n)throw new N;const i="data"in e&&e.data!=null?e.data.constructor.name:void 0,{origin_id:s,origin_slot:a}=e;if(s==null||a==null)return new _.ContextMenu(["Link has no origin"],{event:t,title:i}),!1;const r=n.getNodeById(s),l=r?.outputs?.[a]?.type,d=new _.ContextMenu(["Add Node","Add Reroute",null,"Delete",null],{event:t,title:i,callback:u.bind(this)});return!1;function u(p,m,g){if(!n)throw new N;switch(p){case"Add Node":L.onMenuAdd(null,null,g,d,f=>{if(!f?.inputs?.length||!f?.outputs?.length||a==null)return;const y={afterRerouteId:e.parentId};r?.connectByType(a,f,l??"*",y)&&(f.pos[0]-=f.size[0]*.5)});break;case"Add Reroute":try{this.emitBeforeChange(),this.adjustMouseEvent(g),n.createReroute(e._pos,e),this.setDirty(!1,!0)}catch(f){console.error(f)}finally{this.emitAfterChange()}break;case"Delete":{const f=e instanceof J?e.linkIds.values().next().value:e.id;f!==void 0&&(n.removeLink(f),D.deleteLinkLayout(f));break}default:}}}createDefaultNodeForSlot(e){const t=Object.assign({nodeFrom:null,slotFrom:null,nodeTo:null,slotTo:null,position:[0,0],nodeType:void 0,posAdd:[0,0],posSizeFix:[0,0]},e),{afterRerouteId:n}=t,i=t.nodeFrom&&t.slotFrom!==null,s=!i&&t.nodeTo&&t.slotTo!==null;if(!i&&!s)return console.warn("No data passed to createDefaultNodeForSlot",t.nodeFrom,t.slotFrom,t.nodeTo,t.slotTo),!1;if(!t.nodeType)return console.warn("No type to createDefaultNodeForSlot"),!1;const a=i?t.nodeFrom:t.nodeTo;if(!a)throw new TypeError("nodeX was null when creating default node for slot.");let r=i?t.slotFrom:t.slotTo,l=!1;if(a instanceof _e){if(typeof r!="object"||!r)return console.warn("Cant get slot information",r),!1;const{name:p}=r;if(l=a.slots.findIndex(m=>m.name===p),r=a.slots[l],!r)return console.warn("Cant get slot information",r),!1}else switch(typeof r){case"string":l=i?a.findOutputSlot(r,!1):a.findInputSlot(r,!1),r=i?a.outputs[r]:a.inputs[r];break;case"object":if(r===null)return console.warn("Cant get slot information",r),!1;l=i?a.findOutputSlot(r.name):a.findInputSlot(r.name);break;case"number":l=r,r=i?a.outputs[r]:a.inputs[r];break;case"undefined":default:return console.warn("Cant get slot information",r),!1}const d=r.type==_.EVENT?"_event_":r.type,u=i?_.slot_types_default_out:_.slot_types_default_in;if(u?.[d]){let p=!1;if(typeof u[d]=="object"){for(const m in u[d])if(t.nodeType==u[d][m]||t.nodeType=="AUTO"){p=u[d][m];break}}else(t.nodeType==u[d]||t.nodeType=="AUTO")&&(p=u[d]);if(p){let m,g;typeof p=="object"?(m=p,g=m.node??""):g=p;const f=t.posSizeFix[0]*_.NODE_WIDTH,y=t.posSizeFix[1]*_.NODE_SLOT_HEIGHT,b=[t.position[0]+t.posAdd[0]+f,t.position[1]+t.posAdd[1]+y],v=_.createNode(g,m?.title,{pos:b});if(v){if(m){if(m.properties)for(const w in m.properties)v.addProperty(w,m.properties[w]);if(m.inputs){v.inputs=[];for(const w of m.inputs)v.addInput(w[0],w[1])}if(m.outputs){v.outputs=[];for(const w of m.outputs)v.addOutput(w[0],w[1])}m.json&&v.configure(m.json)}if(!this.graph)throw new N;this.graph.add(v);const k={node:v,opts:t};if(!this.canvas.dispatchEvent(new CustomEvent("connect-new-default-node",{detail:k,cancelable:!0})))return!0;if(i){if(!t.nodeFrom)throw new TypeError("createDefaultNodeForSlot - nodeFrom was null");t.nodeFrom.connectByType(l,v,d,{afterRerouteId:n})}else{if(!t.nodeTo)throw new TypeError("createDefaultNodeForSlot - nodeTo was null");t.nodeTo.connectByTypeOutput(l,v,d,{afterRerouteId:n})}return!0}console.error(`failed creating ${p}`)}}return!1}showConnectionMenu(e){const t=Object.assign({nodeFrom:null,slotFrom:null,nodeTo:null,slotTo:null,e:void 0,allow_searchbox:this.allow_searchbox,showSearchBox:this.showSearchBox},e||{}),n=h(()=>this.#r(),"dirty"),i=this,{graph:s}=this,{afterRerouteId:a}=t,r=t.nodeFrom&&t.slotFrom,l=!r&&t.nodeTo&&t.slotTo;if(!r&&!l){console.warn("No data passed to showConnectionMenu");return}const d=r?t.nodeFrom:t.nodeTo;if(!d)throw new TypeError("nodeX was null when creating default node for slot.");let u=r?t.slotFrom:t.slotTo,p;if(d instanceof _e){if(typeof u!="object"||!u){console.warn("Cant get slot information",u);return}const{name:v}=u;if(p=d.slots.findIndex(k=>k.name===v),p!==-1&&(u=d.slots[p]),!u){console.warn("Cant get slot information",u);return}}else switch(typeof u){case"string":p=r?d.findOutputSlot(u,!1):d.findInputSlot(u,!1),u=r?d.outputs[u]:d.inputs[u];break;case"object":if(u===null){console.warn("Cant get slot information",u);return}p=r?d.findOutputSlot(u.name):d.findInputSlot(u.name);break;case"number":p=u,u=r?d.outputs[u]:d.inputs[u];break;default:console.warn("Cant get slot information",u);return}const m=["Add Node","Add Reroute",null];t.allow_searchbox&&m.push("Search",null);const g=u.type==_.EVENT?"_event_":u.type,f=r?_.slot_types_default_out:_.slot_types_default_in;if(f?.[g])if(typeof f[g]=="object")for(const v in f[g])m.push(f[g][v]);else m.push(f[g]);const y=new _.ContextMenu(m,{event:t.e,extra:u,title:(u&&u.name!=""?u.name+(g?" | ":""):"")+(u&&g?g:""),callback:b});return y;function b(v,k,w){switch(v){case"Add Node":L.onMenuAdd(null,null,w,y,function(S){if(S)if(r){if(!t.nodeFrom)throw new TypeError("Cannot add node to SubgraphInputNode: nodeFrom was null");t.nodeFrom.connectByType(p,S,g,{afterRerouteId:a})||console.warn("Failed to make new connection.")}else{if(!t.nodeTo)throw new TypeError("Cannot add node to SubgraphInputNode: nodeTo was null");t.nodeTo.connectByTypeOutput(p,S,g,{afterRerouteId:a})}});break;case"Add Reroute":{const S=r?t.nodeFrom:t.nodeTo,E=k.extra;if(!s)throw new N;if(!S)throw new TypeError("Cannot add reroute: node was null");if(!E)throw new TypeError("Cannot add reroute: slot was null");if(!t.e)throw new TypeError("Cannot add reroute: CanvasPointerEvent was null");if(S instanceof _e)throw new TypeError("Cannot add floating reroute to Subgraph IO Nodes");if(!S.connectFloatingReroute([t.e.canvasX,t.e.canvasY],E,a))throw new Error("Failed to create reroute");n();break}case"Search":r?t.showSearchBox(w,{node_from:t.nodeFrom,slot_from:u,type_filter_in:g}):t.showSearchBox(w,{node_to:t.nodeTo,slot_from:u,type_filter_out:g});break;default:{const S={position:[t.e?.canvasX??0,t.e?.canvasY??0],nodeType:v,afterRerouteId:a},E=Object.assign(t,S);if(!i.createDefaultNodeForSlot(E))break}}}}prompt(e,t,n,i,s){const a=this;e=e||"";const r={is_modified:!1,className:"graphdialog rounded",innerHTML:s?"<span class='name'></span> <textarea autofocus class='value'></textarea><button class='rounded'>OK</button>":"<span class='name'></span> <input autofocus type='text' class='value'/><button class='rounded'>OK</button>",close(){a.prompt_box=null,d.parentNode&&d.remove()}},l=document.createElement("div"),d=Object.assign(l,r),{canvas:u}=L.active_canvas;if(!u.parentNode)throw new TypeError("canvas element parentNode was null when opening a prompt.");u.parentNode.append(d),this.ds.scale>1&&(d.style.transform=`scale(${this.ds.scale})`);let p,m=0;_.pointerListenerAdd(d,"leave",function(){m||_.dialog_close_on_mouse_leave&&!d.is_modified&&_.dialog_close_on_mouse_leave&&(p=setTimeout(d.close,_.dialog_close_on_mouse_leave_delay))}),_.pointerListenerAdd(d,"enter",function(){_.dialog_close_on_mouse_leave&&p&&clearTimeout(p)});const g=d.querySelectorAll("select");if(g)for(const E of g)E.addEventListener("click",function(){m++}),E.addEventListener("blur",function(){m=0}),E.addEventListener("change",function(){m=-1});this.prompt_box?.close(),this.prompt_box=d;const f=d.querySelector(".name");if(!f)throw new TypeError("name_element was null");f.textContent=e;const y=d.querySelector(".value");if(!y)throw new TypeError("value_element was null");y.value=String(t),y.select();const b=y;b.addEventListener("keydown",function(E){if(d.is_modified=!0,E.key=="Escape")d.close();else if(E.key=="Enter"&&E.target.localName!="textarea")n&&n(this.value),d.close();else return;E.preventDefault(),E.stopPropagation()});const v=d.querySelector("button");if(!v)throw new TypeError("button was null when opening prompt");v.addEventListener("click",function(){n?.(b.value),a.setDirty(!0),d.close()});const k=u.getBoundingClientRect();let w=-20,S=-20;return k&&(w-=k.left,S-=k.top),i?(d.style.left=`${i.clientX+w}px`,d.style.top=`${i.clientY+S}px`):(d.style.left=`${u.width*.5+w}px`,d.style.top=`${u.height*.5+S}px`),setTimeout(function(){b.focus();const E=Date.now();function C(I){I.target===u&&Date.now()-E>256&&(d.close(),u.parentElement?.removeEventListener("click",C),u.parentElement?.removeEventListener("touchend",C))}h(C,"handleOutsideClick"),u.parentElement?.addEventListener("click",C),u.parentElement?.addEventListener("touchend",C)},10),d}showSearchBox(e,t){const n={slot_from:null,node_from:null,node_to:null,do_type_filter:_.search_filter_enabled,type_filter_in:!1,type_filter_out:!1,show_general_if_none_on_typefilter:!0,show_general_after_typefiltered:!0,hide_on_mouse_leave:_.search_hide_on_mouse_leave,show_all_if_empty:!0,show_all_on_open:_.search_show_all_on_open};Object.assign(n,t);const i=this,s=L.active_canvas,{canvas:a}=s,r=a.ownerDocument||document,l=document.createElement("div"),d=Object.assign(l,{close(){i.search_box=void 0,this.blur(),a.focus(),r.body.style.overflow="",setTimeout(()=>a.focus(),20),d.remove()}});d.className="litegraph litesearchbox graphdialog rounded",d.innerHTML="<span class='name'>Search</span> <input autofocus type='text' class='value rounded'/>",n.do_type_filter&&(d.innerHTML+="<select class='slot_in_type_filter'><option value=''></option></select>",d.innerHTML+="<select class='slot_out_type_filter'><option value=''></option></select>");const u=document.createElement("div");u.className="helper",d.append(u),r.fullscreenElement?r.fullscreenElement.append(d):(r.body.append(d),r.body.style.overflow="hidden");let p,m;if(n.do_type_filter&&(p=d.querySelector(".slot_in_type_filter"),m=d.querySelector(".slot_out_type_filter")),this.ds.scale>1&&(d.style.transform=`scale(${this.ds.scale})`),n.hide_on_mouse_leave){let A=0,F=null;if(_.pointerListenerAdd(d,"enter",function(){F&&(clearTimeout(F),F=null)}),d.addEventListener("pointerleave",function(){if(A)return;const T=n.hide_on_mouse_leave,$=typeof T=="number"?T:500;F=setTimeout(d.close,$)}),n.do_type_filter){if(!p)throw new TypeError("selIn was null when showing search box");if(!m)throw new TypeError("selOut was null when showing search box");p.addEventListener("click",function(){A++}),p.addEventListener("blur",function(){A=0}),p.addEventListener("change",function(){A=-1}),m.addEventListener("click",function(){A++}),m.addEventListener("blur",function(){A=0}),m.addEventListener("change",function(){A=-1})}}i.search_box?.close(),i.search_box=d;let g=null,f=null,y=null;const b=d.querySelector("input");if(!b)throw new TypeError("Could not create search input box.");const v=b;if(v&&(v.addEventListener("blur",function(){this.focus()}),v.addEventListener("keydown",function(A){if(A.key=="ArrowUp")I(!1);else if(A.key=="ArrowDown")I(!0);else if(A.key=="Escape")d.close();else if(A.key=="Enter")y instanceof HTMLElement?C(unescape(String(y.dataset.type))):g?C(g):d.close();else{f&&clearInterval(f),f=setTimeout(P,10);return}return A.preventDefault(),A.stopPropagation(),A.stopImmediatePropagation(),!0})),n.do_type_filter){if(p){const A=_.slot_types_in,F=A.length;(n.type_filter_in==_.EVENT||n.type_filter_in==_.ACTION)&&(n.type_filter_in="_event_");for(let T=0;T<F;T++){const $=document.createElement("option");$.value=A[T],$.innerHTML=A[T],p.append($),n.type_filter_in!==!1&&String(n.type_filter_in).toLowerCase()==String(A[T]).toLowerCase()&&($.selected=!0)}p.addEventListener("change",function(){P()})}if(m){const A=_.slot_types_out;(n.type_filter_out==_.EVENT||n.type_filter_out==_.ACTION)&&(n.type_filter_out="_event_");for(const F of A){const T=document.createElement("option");T.value=F,T.innerHTML=F,m.append(T),n.type_filter_out!==!1&&String(n.type_filter_out).toLowerCase()==String(F).toLowerCase()&&(T.selected=!0)}m.addEventListener("change",function(){P()})}}const k=a.getBoundingClientRect(),w=e??new MouseEvent("click",{clientX:k.left+k.width*.5,clientY:k.top+k.height*.5,layerY:k.top+k.height*.5}),S=w.clientX-80,E=w.clientY-20;d.style.left=`${S}px`,d.style.top=`${E}px`,w.layerY>k.height-200&&(u.style.maxHeight=`${k.height-w.layerY-20}px`),requestAnimationFrame(function(){v.focus()}),n.show_all_on_open&&P();function C(A){if(A)if(i.onSearchBoxSelection)i.onSearchBoxSelection(A,w,s);else{if(!s.graph)throw new N;s.graph.beforeChange();const F=_.createNode(A);if(F&&(F.pos=s.convertEventToCanvasOffset(w),s.graph.add(F,!1)),n.node_from){let T=!1;switch(typeof n.slot_from){case"string":T=n.node_from.findOutputSlot(n.slot_from);break;case"object":if(n.slot_from==null)throw new TypeError("options.slot_from was null when showing search box");T=n.slot_from.name?n.node_from.findOutputSlot(n.slot_from.name):-1,T==-1&&n.slot_from.slot_index!==void 0&&(T=n.slot_from.slot_index);break;case"number":T=n.slot_from;break;default:T=0}if(T!==!1&&n.node_from.outputs[T]!==void 0&&T>-1){if(F==null)throw new TypeError("options.slot_from was null when showing search box");n.node_from.connectByType(T,F,n.node_from.outputs[T].type)}}if(n.node_to){let T=!1;switch(typeof n.slot_from){case"string":T=n.node_to.findInputSlot(n.slot_from);break;case"object":if(n.slot_from==null)throw new TypeError("options.slot_from was null when showing search box");T=n.slot_from.name?n.node_to.findInputSlot(n.slot_from.name):-1,T==-1&&n.slot_from.slot_index!==void 0&&(T=n.slot_from.slot_index);break;case"number":T=n.slot_from;break;default:T=0}if(T!==!1&&n.node_to.inputs[T]!==void 0&&T>-1){if(F==null)throw new TypeError("options.slot_from was null when showing search box");n.node_to.connectByTypeOutput(T,F,n.node_to.inputs[T].type)}}s.graph.afterChange()}d.close()}h(C,"select");function I(A){const F=y;y?y instanceof Element&&(y.classList.remove("selected"),y=A?y.nextSibling:y.previousSibling,y||=F):y=A?u.childNodes[0]:u.childNodes[u.childNodes.length],y instanceof Element&&(y.classList.add("selected"),y.scrollIntoView({block:"end",behavior:"smooth"}))}h(I,"changeSelection");function P(){f=null;let A=v.value;if(g=null,u.innerHTML="",!A&&!n.show_all_if_empty)return;if(i.onSearchBox){const T=i.onSearchBox(u,A,s);if(T)for(const $ of T)F($)}else{let me=function(Y,K){K=K||{};const Q=Object.assign({skipFilter:!1,inTypeOverride:!1,outTypeOverride:!1},K),ne=_.registered_node_types[Y];if($&&ne.filter!=$||(!n.show_all_if_empty||A)&&!Y.toLowerCase().includes(A)&&(!ne.title||!ne.title.toLowerCase().includes(A)))return!1;if(n.do_type_filter&&!Q.skipFilter){const Ie=Y;let he=typeof Q.inTypeOverride=="string"?Q.inTypeOverride:V?.value;if(V&&he&&_.registered_slot_in_types[he]?.nodes&&_.registered_slot_in_types[he].nodes.includes(Ie)===!1||(he=oe?.value,typeof Q.outTypeOverride=="string"&&(he=Q.outTypeOverride),oe&&he&&_.registered_slot_out_types[he]?.nodes&&_.registered_slot_out_types[he].nodes.includes(Ie)===!1))return!1}return!0};h(me,"inner_test_filter");let T=0;if(A=A.toLowerCase(),!s.graph)throw new N;const $=s.filter||s.graph.filter;let V=null,oe=null;n.do_type_filter&&i.search_box&&(V=i.search_box.querySelector(".slot_in_type_filter"),oe=i.search_box.querySelector(".slot_out_type_filter"));const x=Object.keys(_.registered_node_types).filter(Y=>me(Y));for(const Y of x)if(F(Y),L.search_limit!==-1&&T++>L.search_limit)break;if(n.show_general_after_typefiltered&&(V?.value||oe?.value)){const Y=[];for(const K in _.registered_node_types)me(K,{inTypeOverride:V&&V.value?"*":!1,outTypeOverride:oe&&oe.value?"*":!1})&&Y.push(K);for(const K of Y)if(F(K,"generic_type"),L.search_limit!==-1&&T++>L.search_limit)break}if((V?.value||oe?.value)&&u.childNodes.length==0&&n.show_general_if_none_on_typefilter){const Y=[];for(const K in _.registered_node_types)me(K,{skipFilter:!0})&&Y.push(K);for(const K of Y)if(F(K,"not_in_filter"),L.search_limit!==-1&&T++>L.search_limit)break}}function F(T,$){const V=document.createElement("div");g||=T;const oe=_.registered_node_types[T];if(oe?.title){V.textContent=oe?.title;const x=document.createElement("span");x.className="litegraph lite-search-item-type",x.textContent=T,V.append(x)}else V.textContent=T;V.dataset.type=escape(T),V.className="litegraph lite-search-item",$&&(V.className+=` ${$}`),V.addEventListener("click",function(){C(unescape(String(this.dataset.type)))}),u.append(V)}h(F,"addResult")}return h(P,"refreshHelper"),d}showEditPropertyValue(e,t,n){if(!e||e.properties[t]===void 0)return;n=n||{};const i=e.getPropertyInfo(t),{type:s}=i;let a="";if(s=="string"||s=="number"||s=="array"||s=="object")a="<input autofocus type='text' class='value'/>";else if((s=="enum"||s=="combo")&&i.values){a="<select autofocus type='text' class='value'>";for(const g in i.values){const f=Array.isArray(i.values)?i.values[g]:g,y=f==e.properties[t]?"selected":"";a+=`<option value='${f}' ${y}>${i.values[g]}</option>`}a+="</select>"}else if(s=="boolean"||s=="toggle")a=`<input autofocus type='checkbox' class='value' ${e.properties[t]?"checked":""}/>`;else{console.warn(`unknown type: ${s}`);return}const r=this.createDialog(`<span class='name'>${i.label||t}</span>${a}<button>OK</button>`,n);let l;if((s=="enum"||s=="combo")&&i.values)l=r.querySelector("select"),l?.addEventListener("change",function(g){r.modified(),m(g.target?.value)});else if(s=="boolean"||s=="toggle")l=r.querySelector("input"),l?.addEventListener("click",function(){r.modified(),m(!!l.checked)});else if(l=r.querySelector("input"),l){l.addEventListener("blur",function(){this.focus()});let g=e.properties[t]!==void 0?e.properties[t]:"";s!=="string"&&(g=JSON.stringify(g)),l.value=g,l.addEventListener("keydown",function(f){if(f.key=="Escape")r.close();else if(f.key=="Enter")u();else{r.modified();return}f.preventDefault(),f.stopPropagation()})}l?.focus();const d=r.querySelector("button");if(!d)throw new TypeError("Show edit property value button was null.");d.addEventListener("click",u);function u(){m(l?.value)}h(u,"inner");const p=h(()=>this.#r(),"dirty");function m(g){i?.values&&typeof i.values=="object"&&i.values[g]!=null&&(g=i.values[g]),typeof e.properties[t]=="number"&&(g=Number(g)),(s=="array"||s=="object")&&(g=JSON.parse(g)),e.properties[t]=g,e.graph&&e.graph._version++,e.onPropertyChanged?.(t,g),n.onclose?.(),r.close(),p()}return h(m,"setValue"),r}createDialog(e,t){t=Object.assign({checkForInput:!1,closeOnLeave:!0,closeOnLeave_checkModified:!0},t||{});const n={className:"graphdialog",innerHTML:e,is_modified:!1,modified(){this.is_modified=!0},close(){this.remove()}},i=document.createElement("div"),s=Object.assign(i,n),a=this.canvas.getBoundingClientRect();let r=-20,l=-20;if(a&&(r-=a.left,l-=a.top),t.position?(r+=t.position[0],l+=t.position[1]):t.event?(r+=t.event.clientX,l+=t.event.clientY):(r+=this.canvas.width*.5,l+=this.canvas.height*.5),s.style.left=`${r}px`,s.style.top=`${l}px`,!this.canvas.parentNode)throw new TypeError("Canvas parent element was null.");if(this.canvas.parentNode.append(s),t.checkForInput){const m=s.querySelectorAll("input");if(m)for(const g of m)g.addEventListener("keydown",function(f){if(s.modified(),f.key=="Escape")s.close();else if(f.key!="Enter")return;f.preventDefault(),f.stopPropagation()}),g.focus()}let d,u=0;s.addEventListener("mouseleave",function(){u||!s.is_modified&&_.dialog_close_on_mouse_leave&&(d=setTimeout(s.close,_.dialog_close_on_mouse_leave_delay))}),s.addEventListener("mouseenter",function(){(t.closeOnLeave||_.dialog_close_on_mouse_leave)&&d&&clearTimeout(d)});const p=s.querySelectorAll("select");if(p)for(const m of p)m.addEventListener("click",function(){u++}),m.addEventListener("blur",function(){u=0}),m.addEventListener("change",function(){u=-1});return s}createPanel(e,t){t=t||{};const n=document.createElement("div");if(n.className="litegraph dialog",n.innerHTML="<div class='dialog-header'><span class='dialog-title'></span></div><div class='dialog-content'></div><div style='display:none;' class='dialog-alt-content'></div><div class='dialog-footer'></div>",n.header=n.querySelector(".dialog-header"),t.width&&(n.style.width=t.width+(typeof t.width=="number"?"px":"")),t.height&&(n.style.height=t.height+(typeof t.height=="number"?"px":"")),t.closable){const i=document.createElement("span");i.innerHTML="✕",i.classList.add("close"),i.addEventListener("click",function(){n.close()}),n.header.append(i)}return n.title_element=n.querySelector(".dialog-title"),n.title_element.textContent=e,n.content=n.querySelector(".dialog-content"),n.alt_content=n.querySelector(".dialog-alt-content"),n.footer=n.querySelector(".dialog-footer"),n.footer.style.marginTop="-96px",n.close=function(){typeof n.onClose=="function"&&n.onClose(),n.remove(),this.remove()},n.toggleAltContent=function(i){let s,a;i!==void 0?(s=i?"block":"none",a=i?"none":"block"):(s=n.alt_content.style.display!="block"?"block":"none",a=n.alt_content.style.display!="block"?"none":"block"),n.alt_content.style.display=s,n.content.style.display=a},n.toggleFooterVisibility=function(i){let s;i!==void 0?s=i?"block":"none":s=n.footer.style.display!="block"?"block":"none",n.footer.style.display=s},n.clear=function(){this.content.innerHTML=""},n.addHTML=function(i,s,a){const r=document.createElement("div");return s&&(r.className=s),r.innerHTML=i,a?n.footer.append(r):n.content.append(r),r},n.addButton=function(i,s,a){const r=document.createElement("button");return r.textContent=i,r.options=a,r.classList.add("btn"),r.addEventListener("click",s),n.footer.append(r),r},n.addSeparator=function(){const i=document.createElement("div");i.className="separator",n.content.append(i)},n.addWidget=function(i,s,a,r,l){r=r||{};let d=String(a);i=i.toLowerCase(),i=="number"&&typeof a=="number"&&(d=a.toFixed(3));const u=document.createElement("div");u.className="property",u.innerHTML="<span class='property_name'></span><span class='property_value'></span>";const p=u.querySelector(".property_name");if(!p)throw new TypeError("Property name element was null.");p.textContent=r.label||s;const m=u.querySelector(".property_value");if(!m)throw new TypeError("Property name element was null.");if(m.textContent=d,u.dataset.property=s,u.dataset.type=r.type||i,u.options=r,u.value=a,i=="code")u.addEventListener("click",function(){const f=this.dataset.property;f&&n.inner_showCodePad?.(f)});else if(i=="boolean")u.classList.add("boolean"),a&&u.classList.add("bool-on"),u.addEventListener("click",()=>{const f=u.dataset.property;if(u.value=!u.value,u.classList.toggle("bool-on"),!m)throw new TypeError("Property name element was null.");m.textContent=u.value?"true":"false",g(f,u.value)});else if(i=="string"||i=="number"){if(!m)throw new TypeError("Property name element was null.");m.setAttribute("contenteditable","true"),m.addEventListener("keydown",function(f){f.code=="Enter"&&(i!="string"||!f.shiftKey)&&(f.preventDefault(),this.blur())}),m.addEventListener("blur",function(){let f=this.textContent;const y=this.parentElement?.dataset.property;this.parentElement?.dataset.type=="number"&&(f=Number(f)),g(y,f)})}else if(i=="enum"||i=="combo"){const f=L.getPropertyPrintableValue(a,r.values);if(!m)throw new TypeError("Property name element was null.");m.textContent=f??"",m.addEventListener("click",function(y){const b=r?.values||[],v=this.parentElement?.dataset.property,k=h(w=>(this.textContent=w??null,g(v,w),!1),"inner_clicked");new _.ContextMenu(b,{event:y,className:"dark",callback:k})})}n.content.append(u);function g(f,y){const b=r||{};b.callback?.(f,y,b),l?.(f,y,b)}return h(g,"innerChange"),u},typeof n.onOpen=="function"&&n.onOpen(),n}closePanels(){document.querySelector("#node-panel")?.close?.(),document.querySelector("#option-panel")?.close?.()}showShowNodePanel(e){this.SELECTED_NODE=e,this.closePanels();const t=this.getCanvasWindow(),n=this.createPanel(e.title||"",{closable:!0,window:t,onOpen:h(()=>{this.NODEPANEL_IS_OPEN=!0},"onOpen"),onClose:h(()=>{this.NODEPANEL_IS_OPEN=!1,this.node_panel=void 0},"onClose")});this.node_panel=n,n.id="node-panel",n.node=e,n.classList.add("settings"),n.style.position="absolute",n.style.top="96px",n.style.left="65px";const i=h(()=>{n.content.innerHTML="",n.addHTML(`<span class='node_type'>${e.type}</span><span class='node_desc'>${e.constructor.desc||""}</span><span class='separator'></span>`),n.addHTML("<h3>Properties</h3>");const s=h((l,d)=>{if(!this.graph)throw new N;if(l){switch(this.graph.beforeChange(e),l){case"Title":if(typeof d!="string")throw new TypeError("Attempting to set title to non-string value.");e.title=d;break;case"Mode":{if(typeof d!="string")throw new TypeError("Attempting to set mode to non-string value.");const u=Object.values(_.NODE_MODES).indexOf(d);u!==-1&&_.NODE_MODES[u]?e.changeMode(u):console.warn(`unexpected mode: ${d}`);break}case"Color":if(typeof d!="string")throw new TypeError("Attempting to set colour to non-string value.");L.node_colors[d]?(e.color=L.node_colors[d].color,e.bgcolor=L.node_colors[d].bgcolor):console.warn(`unexpected color: ${d}`);break;default:e.setProperty(l,d);break}this.graph.afterChange(),this.dirty_canvas=!0}},"fUpdate");n.addWidget("string","Title",e.title,{},s);const a=e.mode==null?void 0:_.NODE_MODES[e.mode];n.addWidget("combo","Mode",a,{values:_.NODE_MODES},s);const r=e.color!==void 0?Object.keys(L.node_colors).filter(function(l){return L.node_colors[l].color==e.color}):"";n.addWidget("combo","Color",r,{values:Object.keys(L.node_colors)},s);for(const l in e.properties){const d=e.properties[l],u=e.getPropertyInfo(l);e.onAddPropertyToPanel?.(l,n)||n.addWidget(u.widget||u.type,l,d,u,s)}n.addSeparator(),e.onShowCustomPanelInfo?.(n),n.footer.innerHTML="",n.addButton("Delete",function(){if(!e.block_delete){if(!e.graph)throw new N;e.graph.remove(e),n.close()}}).classList.add("delete")},"inner_refresh");if(n.inner_showCodePad=function(s){n.classList.remove("settings"),n.classList.add("centered"),n.alt_content.innerHTML="<textarea class='code'></textarea>";const a=n.alt_content.querySelector("textarea"),r=h(function(){n.toggleAltContent(!1),n.toggleFooterVisibility(!0),a.remove(),n.classList.add("settings"),n.classList.remove("centered"),i()},"fDoneWith");a.value=String(e.properties[s]),a.addEventListener("keydown",function(u){u.code=="Enter"&&u.ctrlKey&&(e.setProperty(s,a.value),r())}),n.toggleAltContent(!0),n.toggleFooterVisibility(!1),a.style.height="calc(100% - 40px)";const l=n.addButton("Assign",function(){e.setProperty(s,a.value),r()});n.alt_content.append(l);const d=n.addButton("Close",r);d.style.float="right",n.alt_content.append(d)},i(),!this.canvas.parentNode)throw new TypeError("showNodePanel - this.canvas.parentNode was null");this.canvas.parentNode.append(n)}checkPanels(){if(!this.canvas)return;if(!this.canvas.parentNode)throw new TypeError("checkPanels - this.canvas.parentNode was null");const e=this.canvas.parentNode.querySelectorAll(".litegraph.dialog");for(const t of e)t.node&&(!t.node.graph||t.graph!=this.graph)&&t.close()}getCanvasMenuOptions(){let e;this.getMenuOptions?e=this.getMenuOptions():(e=[{content:"Add Node",has_submenu:!0,callback:L.onMenuAdd},{content:"Add Group",callback:L.onGroupAdd},{content:"Paste",callback:h(()=>{this.pasteFromClipboard()},"callback")}],Object.keys(this.selected_nodes).length>1&&e.push({content:"Convert to Subgraph",callback:h(()=>{if(!this.selectedItems.size)throw new Error("Convert to Subgraph: Nothing selected.");this._graph.convertToSubgraph(this.selectedItems)},"callback")},{content:"Align",has_submenu:!0,callback:L.onGroupAlign}));const t=this.getExtraMenuOptions?.(this,e);return Array.isArray(t)?e.concat(t):e}getNodeMenuOptions(e){let t;e.getMenuOptions?t=e.getMenuOptions(this):(t=[{content:"Convert to Subgraph",callback:h(()=>{if(this.selectedItems.size){let i=!1;for(const s of this.selectedItems){const a=s;if(typeof a.type=="string"&&a.type.startsWith("workflow>")&&a.convertToNodes){i=!0;const r=a.convertToNodes();requestAnimationFrame(()=>{if(this.selectItems(r,!0),!this.selectedItems.size)throw new Error("Convert to Subgraph: Nothing selected.");this._graph.convertToSubgraph(this.selectedItems)});return}}if(!i){if(!this.selectedItems.size)throw new Error("Convert to Subgraph: Nothing selected.");this._graph.convertToSubgraph(this.selectedItems)}}else throw new Error("Convert to Subgraph: Nothing selected.")},"callback")},{content:"Properties",has_submenu:!0,callback:L.onShowMenuNodeProperties},{content:"Properties Panel",callback:h(function(i,s,a,r,l){L.active_canvas.showShowNodePanel(l)},"callback")},null,{content:"Title",callback:L.onShowPropertyEditor},{content:"Mode",has_submenu:!0,callback:L.onMenuNodeMode}],e.resizable!==!1&&t.push({content:"Resize",callback:L.onMenuResizeNode}),e.collapsible&&t.push({content:e.collapsed?"Expand":"Collapse",callback:L.onMenuNodeCollapse}),e.widgets?.some(i=>i.advanced)&&t.push({content:e.showAdvanced?"Hide Advanced":"Show Advanced",callback:L.onMenuToggleAdvanced}),t.push({content:e.pinned?"Unpin":"Pin",callback:h(()=>{for(const i in this.selected_nodes)this.selected_nodes[i].pin();this.setDirty(!0,!0)},"callback")},{content:"Colors",has_submenu:!0,callback:L.onMenuNodeColors},{content:"Shapes",has_submenu:!0,callback:L.onMenuNodeShapes},null));const n=e.getExtraMenuOptions?.(this,t);return Array.isArray(n)&&n.length>0&&(n.push(null),t=n.concat(t)),e.clonable!==!1&&t.push({content:"Clone",callback:L.onMenuNodeClone}),Object.keys(this.selected_nodes).length>1&&t.push({content:"Align Selected To",has_submenu:!0,callback:L.onNodeAlign},{content:"Distribute Nodes",has_submenu:!0,callback:L.createDistributeMenu}),t.push(null,{content:"Remove",disabled:!(e.removable!==!1&&!e.block_delete),callback:L.onMenuNodeRemove}),e.graph?.onGetNodeMenuOptions?.(t,e),t}getGroupMenuOptions(e){return console.warn("LGraphCanvas.getGroupMenuOptions is deprecated, use LGraphGroup.getMenuOptions instead"),e.getMenuOptions()}processContextMenu(e,t){let n;const i={event:t,callback:r,extra:e};if(e){i.title=e.displayType??e.type??void 0,L.active_node=e;const l=e.getSlotInPosition(t.canvasX,t.canvasY);if(l){if(n=[],e.getSlotMenuOptions)n=e.getSlotMenuOptions(l);else{(l.output?.links?.length||l.input?.link!=null)&&n.push({content:"Disconnect Links",slot:l});const d=l.input||l.output;if(!d)throw new TypeError("Both in put and output slots were null when processing context menu.");!d.nameLocked&&!("link"in d&&d.widget)&&n.push({content:"Rename Slot",slot:l}),d.removable&&(n.push(null),n.push(d.locked?"Cannot remove":{content:"Remove Slot",slot:l,className:"danger"})),e.getExtraSlotMenuOptions&&n.push(...e.getExtraSlotMenuOptions(l))}i.title=(l.input?l.input.type:l.output.type)||"*",l.input&&l.input.type==_.ACTION&&(i.title="Action"),l.output&&l.output.type==_.EVENT&&(i.title="Event")}else n=this.getNodeMenuOptions(e)}else{if(n=this.getCanvasMenuOptions(),!this.graph)throw new N;if(this.links_render_mode!==ie.HIDDEN_LINK){const d=D.queryRerouteAtPoint({x:t.canvasX,y:t.canvasY});let u;d?u=this.graph.getReroute(d.id):u=this.graph.getRerouteOnPos(t.canvasX,t.canvasY,this.#s),u&&n.unshift({content:"Delete Reroute",callback:h(()=>{if(!this.graph)throw new N;this.graph.removeReroute(u.id)},"callback")},null)}const l=this.graph.getGroupOnPos(t.canvasX,t.canvasY);l&&n.push(null,{content:"Edit Group",has_submenu:!0,submenu:{title:"Group",extra:l,options:l.getMenuOptions()}})}if(!n)return;new _.ContextMenu(n,i);const s=h(l=>this.createDialog("<span class='name'>Name</span><input autofocus type='text'/><button>OK</button>",l),"createDialog"),a=h(()=>this.setDirty(!0),"setDirty");function r(l,d){if(l){if(l.content=="Remove Slot"){if(!e?.graph)throw new N;const u=l.slot;if(!u)throw new TypeError("Found-slot info was null when processing context menu.");e.graph.beforeChange(),u.input?e.removeInput(u.slot):u.output&&e.removeOutput(u.slot),e.graph.afterChange();return}else if(l.content=="Disconnect Links"){if(!e?.graph)throw new N;const u=l.slot;if(!u)throw new TypeError("Found-slot info was null when processing context menu.");e.graph.beforeChange(),u.output?e.disconnectOutput(u.slot):u.input&&e.disconnectInput(u.slot,!0),e.graph.afterChange();return}else if(l.content=="Rename Slot"){if(!e)throw new TypeError("`node` was null when processing the context menu.");const u=l.slot;if(!u)throw new TypeError("Found-slot info was null when processing context menu.");const p=u.input?e.getInputInfo(u.slot):e.getOutputInfo(u.slot),m=s(d),g=m.querySelector("input");g&&p&&(g.value=p.label||"");const f=h(function(){if(!e.graph)throw new N;e.graph.beforeChange(),g?.value&&(p&&(p.label=g.value),a()),m.close(),e.graph.afterChange()},"inner");if(m.querySelector("button")?.addEventListener("click",f),!g)throw new TypeError("Input element was null when processing context menu.");g.addEventListener("keydown",function(y){if(m.is_modified=!0,y.key=="Escape")m.close();else if(y.key=="Enter")f();else if(y.target.localName!="textarea")return;y.preventDefault(),y.stopPropagation()}),g.focus()}}}h(r,"inner_option_clicked")}animateToBounds(e,t={}){const n=h(()=>this.setDirty(!0,!0),"setDirty");this.ds.animateToBounds(e,n,t)}fitViewToSelectionAnimated(e={}){const t=et(this.selectedItems.size?Array.from(this.selectedItems):this.positionableItems);if(!t)throw new TypeError("Attempted to fit to view but could not calculate bounds.");const n=h(()=>this.setDirty(!0,!0),"setDirty");this.ds.animateToBounds(t,n,e)}calculateNewPosition(e,t,n){return{x:e.pos[0]+t,y:e.pos[1]+n}}applyNodePositionUpdates(e,t){for(const{node:n,newPos:i}of e)n.pos[0]=i.x,n.pos[1]=i.y,t.moveNode(n.id,i)}initLayoutMutations(){const e=Ae();return e.setSource(ue.Canvas),e}collectNodesInGroups(e){const t=new Set;for(const n of e)if(n instanceof de)for(const i of n._children)i instanceof q&&t.add(i);return t}moveGroupChildren(e,t,n,i){for(const s of e._children)if(s instanceof q){const a=s;i.push({node:a,newPos:this.calculateNewPosition(a,t,n)})}else s instanceof de||s.move(t,n,!0)}moveChildNodesInGroupVueMode(e,t,n){const i=this.initLayoutMutations(),s=this.collectNodesInGroups(e),a=[];for(const r of e)if(r instanceof q){const l=r;if(s.has(l))continue;a.push({node:l,newPos:this.calculateNewPosition(l,t,n)})}else r instanceof de?(r.move(t,n,!0),this.moveGroupChildren(r,t,n,a)):r.move(t,n,!0);this.applyNodePositionUpdates(a,i)}repositionNodesVueMode(e){const t=this.initLayoutMutations();this.applyNodePositionUpdates(e,t)}},Mo=class{static{h(this,"MapProxyHandler")}getOwnPropertyDescriptor(o,e){const t=this.get(o,e);if(t)return{configurable:!0,enumerable:!0,value:t}}has(o,e){if(typeof e=="symbol")return!1;const t=parseInt(e,10);return o.has(isNaN(t)?e:t)}ownKeys(o){return[...o.keys()].map(String)}get(o,e){if(e in o)return Reflect.get(o,e,o);if(typeof e=="symbol")return;const t=parseInt(e,10);return o.get(isNaN(t)?e:t)}set(o,e,t){if(typeof e=="symbol")return!1;const n=parseInt(e,10);return o.set(isNaN(n)?e:n,t),!0}deleteProperty(o,e){return o.delete(e)}static bindAllMethods(o){o.clear=o.clear.bind(o),o.delete=o.delete.bind(o),o.forEach=o.forEach.bind(o),o.get=o.get.bind(o),o.has=o.has.bind(o),o.set=o.set.bind(o),o.entries=o.entries.bind(o),o.keys=o.keys.bind(o),o.values=o.values.bind(o),o[Symbol.iterator]=o[Symbol.iterator].bind(o)}},Zt=class ge{static{h(this,"LGraph")}static serialisedSchemaVersion=1;static STATUS_STOPPED=1;static STATUS_RUNNING=2;static ConfigureProperties=new Set(["nodes","groups","links","state","reroutes","floatingLinks","id","subgraphs","definitions","inputs","outputs","widgets","inputNode","outputNode","extra"]);id=bt;revision=0;_version=-1;_links=new Map;links;list_of_graphcanvas;status=ge.STATUS_STOPPED;state={lastGroupId:0,lastNodeId:0,lastLinkId:0,lastRerouteId:0};events=new Et;_subgraphs=new Map;_nodes=[];_nodes_by_id={};_nodes_in_order=[];_nodes_executable=null;_groups=[];iteration=0;globaltime=0;runningtime=0;fixedtime=0;fixedtime_lapse=.01;elapsed_time=.01;last_update_time=0;starttime=0;catch_errors=!0;execution_timer_id;errors_in_execution;execution_time;_last_trigger_time;filter;config={};vars={};nodes_executing=[];nodes_actioning=[];nodes_executedAction=[];extra={};version;get empty(){return this._nodes.length+this._groups.length+this.reroutes.size===0}*positionableItems(){for(const e of this._nodes)yield e;for(const e of this._groups)yield e;for(const e of this.reroutes.values())yield e}#e=0;floatingLinksInternal=new Map;get floatingLinks(){return this.floatingLinksInternal}reroutesInternal=new Map;get reroutes(){return this.reroutesInternal}get rootGraph(){return this}get isRootGraph(){return this.rootGraph===this}get last_node_id(){return this.state.lastNodeId}set last_node_id(e){this.state.lastNodeId=e}get last_link_id(){return this.state.lastLinkId}set last_link_id(e){this.state.lastLinkId=e}onTrigger;_input_nodes;constructor(e){const t=this._links;Mo.bindAllMethods(t);const n=new Mo;this.links=new Proxy(t,n),this.list_of_graphcanvas=null,this.clear(),e&&this.configure(e)}clear(){if(this.stop(),this.status=ge.STATUS_STOPPED,this.id=bt,this.revision=0,this.state={lastGroupId:0,lastNodeId:0,lastLinkId:0,lastRerouteId:0},this._version=-1,this._subgraphs.clear(),this._nodes)for(const e of this._nodes)e.onRemoved?.(),this.onNodeRemoved?.(e);this._nodes=[],this._nodes_by_id={},this._nodes_in_order=[],this._nodes_executable=null,this._links.clear(),this.reroutes.clear(),this.floatingLinksInternal.clear(),this.#e=0,this._groups=[],this.iteration=0,this.config={},this.vars={},this.extra={},this.globaltime=0,this.runningtime=0,this.fixedtime=0,this.fixedtime_lapse=.01,this.elapsed_time=.01,this.last_update_time=0,this.starttime=0,this.catch_errors=!0,this.nodes_executing=[],this.nodes_actioning=[],this.nodes_executedAction=[],this.change(),this.canvasAction(e=>e.clear())}get subgraphs(){return this.rootGraph._subgraphs}get nodes(){return this._nodes}get groups(){return this._groups}attachCanvas(e){if(!(e instanceof ce))throw new TypeError("attachCanvas expects an LGraphCanvas instance");this.primaryCanvas=e,this.list_of_graphcanvas??=[],this.list_of_graphcanvas.includes(e)||this.list_of_graphcanvas.push(e),e.graph!==this&&(e.graph?.detachCanvas(e),e.graph=this,e.subgraph=void 0)}detachCanvas(e){e.graph=null;const t=this.list_of_graphcanvas;if(t){const n=t.indexOf(e);n!==-1&&t.splice(n,1)}}start(e){if(this.status!=ge.STATUS_RUNNING)if(this.status=ge.STATUS_RUNNING,this.onPlayEvent?.(),this.sendEventToAllNodes("onStart"),this.starttime=_.getTime(),this.last_update_time=this.starttime,e||=0,e==0&&typeof window<"u"&&window.requestAnimationFrame){const t=h(()=>{this.execution_timer_id==-1&&(window.requestAnimationFrame(t),this.onBeforeStep?.(),this.runStep(1,!this.catch_errors),this.onAfterStep?.())},"on_frame");this.execution_timer_id=-1,t()}else this.execution_timer_id=setInterval(()=>{this.onBeforeStep?.(),this.runStep(1,!this.catch_errors),this.onAfterStep?.()},e)}stop(){this.status!=ge.STATUS_STOPPED&&(this.status=ge.STATUS_STOPPED,this.onStopEvent?.(),this.execution_timer_id!=null&&(this.execution_timer_id!=-1&&clearInterval(this.execution_timer_id),this.execution_timer_id=null),this.sendEventToAllNodes("onStop"))}runStep(e,t,n){e=e||1;const i=_.getTime();this.globaltime=.001*(i-this.starttime);const s=this._nodes_executable||this._nodes;if(!s)return;if(n=n||s.length,t){for(let l=0;l<e;l++){for(let d=0;d<n;++d){const u=s[d];u.mode==H.ALWAYS&&u.onExecute&&u.doExecute?.()}this.fixedtime+=this.fixedtime_lapse,this.onExecuteStep?.()}this.onAfterExecute?.()}else try{for(let l=0;l<e;l++){for(let d=0;d<n;++d){const u=s[d];u.mode==H.ALWAYS&&u.onExecute?.()}this.fixedtime+=this.fixedtime_lapse,this.onExecuteStep?.()}this.onAfterExecute?.(),this.errors_in_execution=!1}catch(l){if(this.errors_in_execution=!0,_.throw_errors)throw l;_.debug&&console.error("Error during execution:",l),this.stop()}const a=_.getTime();let r=a-i;r==0&&(r=1),this.execution_time=.001*r,this.globaltime+=.001*r,this.iteration+=1,this.elapsed_time=(a-this.last_update_time)*.001,this.last_update_time=a,this.nodes_executing=[],this.nodes_actioning=[],this.nodes_executedAction=[]}updateExecutionOrder(){this._nodes_in_order=this.computeExecutionOrder(!1),this._nodes_executable=[];for(const e of this._nodes_in_order)e.onExecute&&this._nodes_executable.push(e)}computeExecutionOrder(e,t){const n=[],i=[],s={},a={},r={};for(const d of this._nodes){if(e&&!d.onExecute)continue;s[d.id]=d;let u=0;if(d.inputs)for(const p of d.inputs)p?.link!=null&&(u+=1);u==0?(i.push(d),t&&(d._level=1)):(t&&(d._level=0),r[d.id]=u)}for(;;){const d=i.shift();if(d===void 0)break;if(n.push(d),delete s[d.id],!!d.outputs){for(const u of d.outputs)if(!(u?.links==null||u.links.length==0))for(const p of u.links){const m=this._links.get(p);if(!m||a[m.id])continue;const g=this.getNodeById(m.target_id);if(g==null){a[m.id]=!0;continue}t&&(d._level??=0,(!g._level||g._level<=d._level)&&(g._level=d._level+1)),a[m.id]=!0,r[g.id]-=1,r[g.id]==0&&i.push(g)}}}for(const d in s)n.push(s[d]);n.length!=this._nodes.length&&_.debug&&console.warn("something went wrong, nodes missing");function l(d){const u=d.length;for(let p=0;p<u;++p)d[p].order=p}return h(l,"setOrder"),l(n),n.sort(function(d,u){const p=d.constructor.priority||d.priority||0,m=u.constructor.priority||u.priority||0;return p==m?d.order-u.order:p-m}),l(n),n}arrange(e,t){e=e||100;const n=this.computeExecutionOrder(!1,!0),i=[];for(const a of n){const r=a._level||1;i[r]||=[],i[r].push(a)}let s=e;for(const a of i){if(!a)continue;let r=100,l=e+_.NODE_TITLE_HEIGHT;for(const d of a){d.pos[0]=t==_.VERTICAL_LAYOUT?l:s,d.pos[1]=t==_.VERTICAL_LAYOUT?s:l;const u=t==_.VERTICAL_LAYOUT?1:0;d.size[u]>r&&(r=d.size[u]);const p=t==_.VERTICAL_LAYOUT?0:1;l+=d.size[p]+e+_.NODE_TITLE_HEIGHT}s+=r+e}this.setDirtyCanvas(!0,!0)}getTime(){return this.globaltime}getFixedTime(){return this.fixedtime}getElapsedTime(){return this.elapsed_time}sendEventToAllNodes(e,t,n){n=n||H.ALWAYS;const i=this._nodes_in_order||this._nodes;if(i)for(const s of i)!s[e]||s.mode!=n||(t===void 0?s[e]():t&&t.constructor===Array?s[e].apply(s,t):s[e](t))}canvasAction(e){const t=this.list_of_graphcanvas;if(t)for(const n of t)e(n)}sendActionToCanvas(e,t){const{list_of_graphcanvas:n}=this;if(n)for(const i of n){const s=i[e];if(typeof s=="function"){const a=t==null?[]:Array.isArray(t)?t:[t];s.apply(i,a)}}}add(e,t){if(!e)return;const{state:n}=this;if(_.alwaysSnapToGrid){const i=this.getSnapToGridSize();i&&e.snapToGrid(i)}if(e instanceof de){(e.id==null||e.id===-1)&&(e.id=++n.lastGroupId),e.id>n.lastGroupId&&(n.lastGroupId=e.id),this._groups.push(e),this.setDirtyCanvas(!0),this.change(),e.graph=this,this._version++;return}if(e.id!=-1&&this._nodes_by_id[e.id]!=null&&(console.warn("LiteGraph: there is already a node with this ID, changing it"),e.id=_.use_uuids?_.uuidv4():++n.lastNodeId),this._nodes.length>=_.MAX_NUMBER_OF_NODES)throw"LiteGraph: max number of nodes in a graph reached";return _.use_uuids?(e.id==null||e.id==-1)&&(e.id=_.uuidv4()):e.id==null||e.id==-1?e.id=++n.lastNodeId:typeof e.id=="number"&&n.lastNodeId<e.id&&(n.lastNodeId=e.id),e.graph=this,this._version++,this._nodes.push(e),this._nodes_by_id[e.id]=e,e.onAdded?.(this),this.config.align_to_grid&&e.alignToGrid(),t||this.updateExecutionOrder(),this.onNodeAdded?.(e),this.setDirtyCanvas(!0),this.change(),e}remove(e){if(e instanceof de){this.canvasAction(r=>r.deselect(e));const a=this._groups.indexOf(e);a!=-1&&this._groups.splice(a,1),e.graph=void 0,this._version++,this.setDirtyCanvas(!0,!0),this.change();return}if(this._nodes_by_id[e.id]==null){console.warn("LiteGraph: node not found",e);return}if(e.ignore_remove){console.warn("LiteGraph: node cannot be removed",e);return}this.beforeChange();const{inputs:t,outputs:n}=e;if(t)for(const[a,r]of t.entries())r.link!=null&&e.disconnectInput(a,!0);if(n)for(const[a,r]of n.entries())r.links?.length&&e.disconnectOutput(a);for(const a of this.floatingLinks.values())(a.origin_id===e.id||a.target_id===e.id)&&this.removeFloatingLink(a);e.onRemoved?.(),e.graph=null,this._version++;const{list_of_graphcanvas:i}=this;if(i)for(const a of i)a.selected_nodes[e.id]&&delete a.selected_nodes[e.id],a.deselect(e);const s=this._nodes.indexOf(e);s!=-1&&this._nodes.splice(s,1),delete this._nodes_by_id[e.id],this.onNodeRemoved?.(e),this.canvasAction(a=>a.checkPanels()),this.setDirtyCanvas(!0,!0),this.afterChange(),this.change(),this.updateExecutionOrder()}getNodeById(e){return e!=null?this._nodes_by_id[e]:null}findNodesByClass(e,t){t=t||[],t.length=0;const{_nodes:n}=this;for(const i of n)i.constructor===e&&t.push(i);return t}findNodesByType(e,t){const n=e.toLowerCase();t=t||[],t.length=0;const{_nodes:i}=this;for(const s of i)s.type?.toLowerCase()==n&&t.push(s);return t}findNodeByTitle(e){const{_nodes:t}=this;for(const n of t)if(n.title==e)return n;return null}findNodesByTitle(e){const t=[],{_nodes:n}=this;for(const i of n)i.title==e&&t.push(i);return t}getNodeOnPos(e,t,n){const i=n||this._nodes;let s=i.length;for(;--s>=0;){const a=i[s];if(a.isPointInside(e,t))return a}return null}getGroupOnPos(e,t){for(let n=this._groups.length-1;n>=0;n--){const i=this._groups[n];if(i.isPointInside(e,t))return i}}getGroupTitlebarOnPos(e,t){for(let n=this._groups.length-1;n>=0;n--){const i=this._groups[n];if(i.isPointInTitlebar(e,t))return i}}getRerouteOnPos(e,t,n){for(const i of n??this.reroutes.values())if(i.containsPoint([e,t]))return i}snapToGrid(e){const t=this.getSnapToGridSize();if(t)for(const n of yn(e))n.pinned||n.snapToGrid(t)}getSnapToGridSize(){return _.alwaysSnapToGrid?_.CANVAS_GRID_SIZE||1:_.CANVAS_GRID_SIZE}checkNodeTypes(){const{_nodes:e}=this;for(const[t,n]of e.entries()){const i=_.registered_node_types[n.type];if(n.constructor==i)continue;console.warn("node being replaced by newer version:",n.type);const s=_.createNode(n.type);s&&(e[t]=s,s.configure(n.serialize()),s.graph=this,this._nodes_by_id[s.id]=s,n.inputs&&(s.inputs=[...n.inputs]),n.outputs&&(s.outputs=[...n.outputs]))}this.updateExecutionOrder()}trigger(e,t){new Set(["node:slot-links:changed","node:slot-errors:changed","node:property:changed"]).has(e)&&t&&typeof t=="object"&&this.onTrigger?.({type:e,...t})}triggerInput(e,t){const n=this.findNodesByTitle(e);for(const i of n)i.onTrigger(t)}setCallback(e,t){const n=this.findNodesByTitle(e);for(const i of n)i.setTrigger(t)}beforeChange(e){this.onBeforeChange?.(this,e),this.canvasAction(t=>t.onBeforeChange?.(this))}afterChange(e){this.onAfterChange?.(this,e),this.canvasAction(t=>t.onAfterChange?.(this))}clearTriggeredSlots(){for(const e of this._links.values())e&&e._last_time&&(e._last_time=0)}change(){this.canvasAction(e=>e.setDirty(!0,!0)),this.on_change?.(this)}setDirtyCanvas(e,t){this.canvasAction(n=>n.setDirty(e,t))}addFloatingLink(e){e.id===-1&&(e.id=++this.#e),this.floatingLinksInternal.set(e.id,e);const t=e.target_id!==-1?this.getNodeById(e.target_id)?.inputs?.[e.target_slot]:this.getNodeById(e.origin_id)?.outputs?.[e.origin_slot];t?(t._floatingLinks??=new Set,t._floatingLinks.add(e)):console.warn(`Adding invalid floating link: target/slot: [${e.target_id}/${e.target_slot}] origin/slot: [${e.origin_id}/${e.origin_slot}]`);const n=z.getReroutes(this,e);for(const i of n)i.floatingLinkIds.add(e.id);return e}removeFloatingLink(e){this.floatingLinksInternal.delete(e.id);const t=e.target_id!==-1?this.getNodeById(e.target_id)?.inputs?.[e.target_slot]:this.getNodeById(e.origin_id)?.outputs?.[e.origin_slot];t&&t._floatingLinks?.delete(e);const n=z.getReroutes(this,e);for(const i of n)i.floatingLinkIds.delete(e.id),i.floatingLinkIds.size===0&&delete i.floating,i.totalLinks===0&&this.removeReroute(i.id)}getLink(e){return e==null?void 0:this._links.get(e)}getReroute(e){return e==null?void 0:this.reroutes.get(e)}setReroute({id:e,parentId:t,pos:n,linkIds:i,floating:s}){e??=++this.state.lastRerouteId,e>this.state.lastRerouteId&&(this.state.lastRerouteId=e);const a=this.reroutes.get(e)??new J(e,this);return a.update(t,n,i,s),this.reroutes.set(e,a),a}createReroute(e,t){const n=Ae(),i=++this.state.lastRerouteId,s=t instanceof J?t.linkIds:[t.id],a=t instanceof J?t.floatingLinkIds:[t.id],r=new J(i,this,e,t.parentId,s,a);this.reroutes.set(i,r),n.setSource(ue.Canvas),n.createReroute(i,{x:e[0],y:e[1]},t.parentId,Array.from(s));for(const l of s){const d=this._links.get(l);if(!d)continue;d.parentId===t.parentId&&(d.parentId=i);const u=z.getReroutes(this,d);for(const p of u.filter(m=>m.parentId===t.parentId))p.parentId=i}for(const l of a){const d=this.floatingLinks.get(l);if(!d)continue;d.parentId===t.parentId&&(d.parentId=i);const u=z.getReroutes(this,d);for(const p of u.filter(m=>m.parentId===t.parentId))p.parentId=i}return r}removeReroute(e){const t=Ae(),{reroutes:n}=this,i=n.get(e);if(!i)return;this.canvasAction(l=>l.deselect(i));const{parentId:s,linkIds:a,floatingLinkIds:r}=i;for(const l of n.values())l.parentId===e&&(l.parentId=s);for(const l of a){const d=this._links.get(l);d&&d.parentId===e&&(d.parentId=s)}for(const l of r){const d=this.floatingLinks.get(l);if(!d){console.warn(`Removed reroute had floating link ID that did not exist [${l}]`);continue}const u=z.getReroutes(this,d),p=u.at(-1),m=u.at(-2);i===p&&(m?.totalLinks!==1?this.removeFloatingLink(d):d.parentId===e&&(d.parentId=s,m.floating=i.floating))}n.delete(e),t.setSource(ue.Canvas),t.deleteReroute(e),this.setDirtyCanvas(!1,!0)}removeLink(e){const t=this._links.get(e);t&&(this.getNodeById(t.target_id)?.disconnectInput(t.target_slot,!1),t.disconnect(this))}createSubgraph(e){const{id:t}=e,n=new De(this.rootGraph,e);return this.subgraphs.set(t,n),this.rootGraph.events.dispatch("subgraph-created",{subgraph:n,data:e}),n}convertToSubgraph(e){if(e.size===0)throw new Error("Cannot convert to subgraph: nothing to convert");this.beforeChange();try{return this._convertToSubgraphImpl(e)}finally{this.afterChange()}}_convertToSubgraphImpl(e){const{state:t,revision:n,config:i}=this,s=[...e][0];e.size===1&&s instanceof de&&(e=new Set([s]),s.recomputeInsideNodes(),s.children.forEach(x=>e.add(x)));const{boundaryLinks:a,boundaryFloatingLinks:r,internalLinks:l,boundaryInputLinks:d,boundaryOutputLinks:u}=Ns(this,e),{nodes:p,reroutes:m,groups:g}=Es(e),f=et(e);if(!f)throw new Error("Failed to create bounding rect for subgraph");const y=d.map(x=>x.resolve(this)),b=u.map(x=>x.resolve(this)),v=No(p),k=l.map(x=>x.asSerialisable()),w=new Map([...m].map(x=>[x.id,x])),S=new Map([...this.reroutes].filter(([x])=>!w.has(x))),E=xs(y,k,w),C=As(b,k,S),I={id:fe(),name:"New Subgraph",inputNode:{id:-10,bounding:[0,0,75,100]},outputNode:{id:-20,bounding:[0,0,75,100]},inputs:E,outputs:C,widgets:[],version:ge.serialisedSchemaVersion,state:t,revision:n,config:i,links:k,nodes:v,reroutes:structuredClone([...m].map(x=>x.asSerialisable())),groups:structuredClone([...g].map(x=>x.serialize()))},P=this.createSubgraph(I);P.configure(I);for(const x of P.nodes)x.onGraphConfigured?.();for(const x of P.nodes)x.onAfterGraphConfigured?.();P.inputNode.arrange(),P.outputNode.arrange();const{boundingRect:A}=P.inputNode,{boundingRect:F}=P.outputNode;po(A,ee.MidLeft,f,[50,0]),po(F,ee.MidRight,f,[50,0]);for(const x of y)x.inputNode?.disconnectInput(x.inputNode.inputs.indexOf(x.input),!0);for(const x of b)x.outputNode?.disconnectOutput(x.outputNode.outputs.indexOf(x.output),x.inputNode);for(const x of p)this.remove(x);for(const x of m)this.removeReroute(x.id);for(const x of g)this.remove(x);this.rootGraph.events.dispatch("convert-to-subgraph",{subgraph:P,bounds:f,exportedSubgraph:I,boundaryLinks:a,resolvedInputLinks:y,resolvedOutputLinks:b,boundaryFloatingLinks:r,internalLinks:l});const T=_.createNode(P.id,P.name,{outputs:structuredClone(C)});if(!T)throw new Error("Failed to create subgraph node");for(let x=0;x<E.length;x++)Object.assign(T.inputs[x],E[x]);T.setSize(T.computeSize()),Hi(T._posSize,ee.Centre|ee.Middle,f),T.pos[1]+=_.NODE_TITLE_HEIGHT/2,this.add(T);const $=St(y);let V=0;for(const[,x]of $.entries()){const[me,...Y]=x,{output:K,outputNode:Q,link:ne,subgraphInput:Ie}=me;if(V++,ne.origin_id===-10){if(ne.target_id=T.id,ne.target_slot=V-1,Ie instanceof kt)Ie.connect(T.findInputSlotByType(ne.type,!0,!0),T,ne.parentId);else throw new TypeError("Subgraph input node is not a SubgraphInput");for(const Kn of Y)Kn.link.disconnect(this);continue}if(!K||!Q){console.warn("Convert to Subgraph reconnect: Failed to resolve input link",x[0]);continue}const he=T.inputs[V-1];Q.connectSlots(K,T,he,ne.parentId)}const oe=St(b);V=0;for(const[,x]of oe.entries()){V++;for(const me of x){const{input:Y,inputNode:K,link:Q,subgraphOutput:ne}=me;if(Q.target_id===-20){if(Q.origin_id=T.id,Q.origin_slot=V-1,this.links.set(Q.id,Q),ne instanceof wt)ne.connect(T.findOutputSlotByType(Q.type,!0,!0),T,Q.parentId);else throw new TypeError("Subgraph input node is not a SubgraphInput");continue}if(!Y||!K){console.warn("Convert to Subgraph reconnect: Failed to resolve output link",me);continue}const Ie=T.outputs[V-1];T.connectSlots(Ie,K,Y,Q.parentId)}}return T._setConcreteSlots(),T.arrange(),this.canvasAction(x=>x.canvas.dispatchEvent(new CustomEvent("subgraph-converted",{bubbles:!0,detail:{subgraphNode:T}}))),{subgraph:P,node:T}}unpackSubgraph(e,t){if(!(e instanceof gt))throw new Error("Can only unpack Subgraph Nodes");this.beforeChange();try{this._unpackSubgraphImpl(e,t)}finally{this.afterChange()}}_unpackSubgraphImpl(e,t){const n=t?.skipMissingNodes??!1,i=et([...e.subgraph.nodes,...e.subgraph.reroutes.values(),...e.subgraph.groups].map(y=>({boundingRect:[y.pos[0],y.pos[1],y.size?.[0]??0,y.size?.[1]??0]})))??[0,0,0,0],s=[i[0]+i[2]/2,i[1]+i[3]/2],a=[],r=e.pos[0]-s[0]+e.size[0]/2,l=e.pos[1]-s[1]+e.size[1]/2,d=No(e.subgraph.nodes),u=new Map;for(const y of d){let b=_.createNode(String(y.type),y.title);if(!b)if(n)console.warn(`Cannot unpack node of type "${y.type}" - node type not found. Creating placeholder node.`),b=new q(y.title||y.type||"Missing Node"),b.last_serialization=y,b.has_errors=!0,b.type=String(y.type);else throw new Error(`Cannot unpack: node type "${y.type}" is not registered`);u.set(y.id,++this.last_node_id),b.id=this.last_node_id,y.id=this.last_node_id,this.add(b,!0),b.configure(y),b.pos[0]+=r,b.pos[1]+=l;for(const v of b.inputs)v.link=null;for(const v of b.outputs)v.links=[];a.push(b)}const p=structuredClone([...e.subgraph.groups].map(y=>y.serialize()));for(const y of p){const b=new de(y.title,y.id);this.add(b,!0),b.configure(y),b.pos[0]+=r,b.pos[1]+=l,a.push(b)}for(const y of e.inputs){if(!y.link)continue;const b=this.links.get(y.link);if(!b){console.warn("Broken link",y,y.link);continue}for(const v of z.getReroutes(this,b))v.linkIds.delete(b.id)}for(const y of e.outputs)for(const b of y.links??[]){const v=this.links.get(b);if(!v){console.warn("Broken link",y,b);continue}for(const k of z.getReroutes(this,v))k.linkIds.delete(v.id)}const m=[];for(const[,y]of e.subgraph._links){let b;if(y.origin_id===-10){const v=e.inputs[y.origin_slot].link;if(!v){console.error("Missing Link ID when unpacking");continue}const k=this.links[v];y.origin_id=k.origin_id,y.origin_slot=k.origin_slot,b=k.parentId}else{const v=u.get(y.origin_id);if(!v){console.error("Missing Link ID when unpacking");continue}y.origin_id=v}if(y.target_id===-20){for(const v of e.outputs[y.target_slot].links??[]){const k=this.links[v];m.push({oid:y.origin_id,oslot:y.origin_slot,tid:k.target_id,tslot:k.target_slot,id:y.id,iparent:y.parentId,eparent:k.parentId,externalFirst:!0}),k.parentId=void 0}continue}else{const v=u.get(y.target_id);if(!v){console.error("Missing Link ID when unpacking");continue}y.target_id=v}m.push({oid:y.origin_id,oslot:y.origin_slot,tid:y.target_id,tslot:y.target_slot,id:y.id,iparent:y.parentId,eparent:b,externalFirst:!1})}this.remove(e),this.subgraphs.delete(e.subgraph.id);const g=new Map;for(const y of m){let b;if(y.oid==-10){if(!(this instanceof De)){console.error("Ignoring link to subgraph outside subgraph");continue}const k=this._nodes_by_id[y.tid];b=this.inputNode.slots[y.oslot].connect(k.inputs[y.tslot],k)}else if(y.tid==-20){if(!(this instanceof De)){console.error("Ignoring link to subgraph outside subgraph");continue}const k=this._nodes_by_id[y.oid];b=this.outputNode.slots[y.tslot].connect(k.outputs[y.oslot],k)}else b=this._nodes_by_id[y.oid].connect(y.oslot,this._nodes_by_id[y.tid],y.tslot);if(!b){console.error("Failed to create link");continue}const v=g.get(y.id)??[];v.push(b.id),g.has(y.id)||g.set(y.id,v),y.id=b.id}const f=new Map;for(const y of e.subgraph.reroutes.values()){y.parentId!==void 0&&f.get(y.parentId)===void 0&&console.error("Missing Parent ID");const b=new J(++this.state.lastRerouteId,this,[y.pos[0]+r,y.pos[1]+l]);f.set(y.id,b.id),this.reroutes.set(b.id,b),a.push(b)}for(const y of m){const b=this.links.get(y.id);if(!b)continue;let v=b,k;if(y.externalFirst)for(k=y.eparent;k;){if(v.parentId=k,v=this.reroutes.get(k),!v){console.error("Broken Id link when unpacking");break}if(v.linkIds.has(b.id))throw new Error("Infinite parentId loop");v.linkIds.add(b.id),k=v.parentId}if(v){for(k=y.iparent;k;){const w=f.get(k);if(!w){console.error("Broken Id link when unpacking");break}if(v.parentId=w,v=this.reroutes.get(w),!v){console.error("Broken Id link when unpacking");break}if(v.linkIds.has(b.id))throw new Error("Infinite parentId loop");v.linkIds.add(b.id);const S=e.subgraph.reroutes.get(k);if(!S){console.error("Broken Id link when unpacking");break}k=S.parentId}if(!v)break;if(!y.externalFirst)for(k=y.eparent;k;){if(v.parentId=k,v=this.reroutes.get(k),!v){console.error("Broken Id link when unpacking");break}if(v.linkIds.has(b.id))throw new Error("Infinite parentId loop");v.linkIds.add(b.id),k=v.parentId}}}for(const y of u.values()){const b=this._nodes_by_id[y];b._setConcreteSlots(),b.arrange()}this.canvasAction(y=>y.selectItems(a))}resolveSubgraphIdPath(e){const t=[];let n=this.rootGraph;for(const i of e){const s=n.getNodeById(i);if(!s)throw new Error(`Node [${i}] not found. ID Path: ${e.join(":")}`);if(!s.isSubgraphNode())throw new Error(`Node [${i}] is not a SubgraphNode. ID Path: ${e.join(":")}`);t.push(s),n=s.subgraph}return t}serialize(e){const{config:t,state:n,groups:i,nodes:s,reroutes:a,extra:r,floatingLinks:l,definitions:d}=this.asSerialisable(e),u=[...this._links.values()],p=u.map(m=>m.serialize());return a?.length&&(r.linkExtensions=u.filter(m=>m.parentId!==void 0).map(m=>({id:m.id,parentId:m.parentId}))),r.reroutes=a?.length?a:void 0,{id:this.id,revision:this.revision,last_node_id:n.lastNodeId,last_link_id:n.lastLinkId,nodes:s,links:p,floatingLinks:l,groups:i,definitions:d,config:t,extra:r,version:_.VERSION}}#t(){const e=this.list_of_graphcanvas?.at(0)?.ds;if(e)return{scale:e.scale,offset:e.offset}}asSerialisable(e){const{id:t,revision:n,config:i,state:s}=this,a=(!_.use_uuids&&e?.sortNodes?[...this._nodes].sort((g,f)=>g.id-f.id):this._nodes).map(g=>g.serialize()),r=this._groups.map(g=>g.serialize()),l=this._links.size?[...this._links.values()].map(g=>g.asSerialisable()):void 0,d=this.floatingLinks.size?[...this.floatingLinks.values()].map(g=>g.asSerialisable()):void 0,u=this.reroutes.size?[...this.reroutes.values()].map(g=>g.asSerialisable()):void 0,p={...this.extra};_.saveViewportWithGraph&&(p.ds=this.#t()),p.ds||delete p.ds;const m={id:t,revision:n,version:ge.serialisedSchemaVersion,config:i,state:s,groups:r,nodes:a,links:l,floatingLinks:d,reroutes:u,extra:p};if(this.isRootGraph&&this._subgraphs.size){const g=Os(this,this._subgraphs),f=[...this._subgraphs.values()].filter(y=>g.has(y.id)).map(y=>y.asSerialisable());f.length>0&&(m.definitions={subgraphs:f})}return this.onSerialize?.(m),m}_configureBase(e){const{id:t,extra:n}=e;t?this.id=t:this.id==="00000000-0000-0000-0000-000000000000"&&(this.id=fe()),this.extra=n?structuredClone(n):{},delete this.extra.linkExtensions}configure(e,t){const n=Ae(),i={data:e,clearGraph:!t};if(this.events.dispatch("configuring",i))try{if(!e)return;i.clearGraph&&this.clear(),this._configureBase(e);let s;if(e.version===.4){const{extra:g}=e;if(Array.isArray(e.links))for(const f of e.links){const y=z.createFromArray(f);this._links.set(y.id,y)}if(Array.isArray(g?.linkExtensions))for(const f of g.linkExtensions){const y=this._links.get(f.id);y&&(y.parentId=f.parentId)}s=g?.reroutes}else{if(e.state){const{lastGroupId:g,lastLinkId:f,lastNodeId:y,lastRerouteId:b}=e.state,{state:v}=this;g!=null&&(v.lastGroupId=g),f!=null&&(v.lastLinkId=f),y!=null&&(v.lastNodeId=y),b!=null&&(v.lastRerouteId=b)}if(Array.isArray(e.links))for(const g of e.links){const f=z.create(g);this._links.set(f.id,f)}s=e.reroutes}if(Array.isArray(s))for(const g of s)this.setReroute(g);const a=e.nodes;for(const g in e)ge.ConfigureProperties.has(g)||(this[g]=e[g]);const r=e.definitions?.subgraphs;if(r){for(const g of r)this.createSubgraph(g);for(const g of r)this.subgraphs.get(g.id)?.configure(g)}let l=!1;const d=new Map;if(this._nodes=[],a){for(const g of a){let f=_.createNode(String(g.type),g.title);f||(_.debug&&console.warn("Node not found or has errors:",g.type),f=new q(""),f.last_serialization=g,f.has_errors=!0,l=!0),f.id=g.id,this.add(f,!0),d.set(f.id,g)}for(const[g,f]of d)this.getNodeById(g)?.configure(f)}if(Array.isArray(e.floatingLinks))for(const g of e.floatingLinks){const f=z.create(g);this.addFloatingLink(f),f.id>this.#e&&(this.#e=f.id)}for(const g of this.reroutes.values())g.validateLinks(this._links,this.floatingLinks)||(this.reroutes.delete(g.id),n.setSource(ue.Canvas),n.deleteReroute(g.id));this._groups.length=0;const u=e.groups;if(u)for(const g of u){const f=new _.LGraphGroup;f.configure(g),this.add(f)}this.updateExecutionOrder(),this.onConfigure?.(e),this._version++;const{primaryCanvas:p}=this,m=p?.subgraph?.id;if(m){const g=this.subgraphs.get(m);g?p.setGraph(g):p.setGraph(this)}return this.setDirtyCanvas(!0,!0),l}finally{this.events.dispatch("configured")}}#o;get primaryCanvas(){return this.rootGraph.#o}set primaryCanvas(e){this.rootGraph.#o=e}load(e,t){if(e instanceof Blob||e instanceof File){const i=new FileReader;i.addEventListener("load",s=>{const a=$t(s.target?.result),r=JSON.parse(a);this.configure(r),t?.()}),i.readAsText(e);return}const n=new XMLHttpRequest;n.open("GET",e,!0),n.send(null),n.addEventListener("load",()=>{if(n.status!==200){console.error("Error loading graph:",n.status,n.response);return}const i=JSON.parse(n.response);this.configure(i),t?.()}),n.addEventListener("error",i=>{console.error("Error loading graph:",i)})}},De=class On extends Zt{static{h(this,"Subgraph")}events=new Et;static MAX_NESTED_SUBGRAPHS=1e3;name="Unnamed Subgraph";inputNode=new Nt(this);outputNode=new xt(this);inputs=[];outputs=[];widgets=[];#e;get rootGraph(){return this.#e}constructor(e,t){if(!e)throw new Error("Root graph is required");super(),this.#e=e;const n=structuredClone(t);this._configureBase(n),this.#t(n)}getIoNodeOnPos(e,t){const{inputNode:n,outputNode:i}=this;if(n.containsPoint([e,t]))return n;if(i.containsPoint([e,t]))return i}#t(e){const{name:t,inputs:n,outputs:i,widgets:s}=e;if(this.name=t,n){this.inputs.length=0;for(const a of n){const r=new kt(a,this.inputNode);this.inputs.push(r),this.events.dispatch("input-added",{input:r})}}if(i){this.outputs.length=0;for(const a of i)this.outputs.push(new wt(a,this.outputNode))}if(s){this.widgets.length=0;for(const a of s)this.widgets.push(a)}this.inputNode.configure(e.inputNode),this.outputNode.configure(e.outputNode)}configure(e,t){const n=super.configure(e,t);return this.#t(e),n}attachCanvas(e){super.attachCanvas(e),e.subgraph=this}addInput(e,t){this.events.dispatch("adding-input",{name:e,type:t});const n=new kt({id:fe(),name:e,type:t},this.inputNode);return this.inputs.push(n),this.events.dispatch("input-added",{input:n}),n}addOutput(e,t){this.events.dispatch("adding-output",{name:e,type:t});const n=new wt({id:fe(),name:e,type:t},this.outputNode);return this.outputs.push(n),this.events.dispatch("output-added",{output:n}),n}renameInput(e,t){const n=this.inputs.indexOf(e);if(n===-1)throw new Error("Input not found");const i=e.displayName;this.events.dispatch("renaming-input",{input:e,index:n,oldName:i,newName:t}),e.label=t}renameOutput(e,t){const n=this.outputs.indexOf(e);if(n===-1)throw new Error("Output not found");const i=e.displayName;this.events.dispatch("renaming-output",{output:e,index:n,oldName:i,newName:t}),e.label=t}removeInput(e){e.disconnect();const t=this.inputs.indexOf(e);if(t===-1)throw new Error("Input not found");if(!this.events.dispatch("removing-input",{input:e,index:t}))return;this.inputs.splice(t,1);const{length:n}=this.inputs;for(let i=t;i<n;i++)this.inputs[i].decrementSlots("inputs")}removeOutput(e){e.disconnect();const t=this.outputs.indexOf(e);if(t===-1)throw new Error("Output not found");if(!this.events.dispatch("removing-output",{output:e,index:t}))return;this.outputs.splice(t,1);const{length:n}=this.outputs;for(let i=t;i<n;i++)this.outputs[i].decrementSlots("outputs")}draw(e,t,n,i){this.inputNode.draw(e,t,n,i),this.outputNode.draw(e,t,n,i)}clone(e=!1){const t=this.asSerialisable();e||(t.id=fe());const n=new On(this.rootGraph,t);return n.configure(t),n}asSerialisable(){return{id:this.id,version:Zt.serialisedSchemaVersion,state:this.state,revision:this.revision,config:this.config,name:this.name,inputNode:this.inputNode.asSerialisable(),outputNode:this.outputNode.asSerialisable(),inputs:this.inputs.map(e=>e.asSerialisable()),outputs:this.outputs.map(e=>e.asSerialisable()),widgets:[...this.widgets],nodes:this.nodes.map(e=>e.serialize()),groups:this.groups.map(e=>e.serialize()),links:[...this.links.values()].map(e=>e.asSerialisable()),reroutes:this.reroutes.size?[...this.reroutes.values()].map(e=>e.asSerialisable()):void 0,extra:this.extra}}},Uw=class{static{h(this,"InputIndicators")}radius=8;startAngle=0;endAngle=Math.PI*2;inactiveColour="#ffffff10";colour1="#ff5f00";colour2="#00ff7c";colour3="#dea7ff";fontString="bold 12px Inter, sans-serif";enabled=!0;shiftDown=!1;undoDown=!1;redoDown=!1;ctrlDown=!1;altDown=!1;mouse0Down=!1;mouse1Down=!1;mouse2Down=!1;x=0;y=0;controller;constructor(o){this.canvas=o,this.controller=new AbortController;const{signal:e}=this.controller,t=o.canvas,n={capture:!0,signal:e};t.addEventListener("pointerdown",this.#e,n),t.addEventListener("pointermove",this.#e,n),t.addEventListener("pointerup",this.#t,n),t.addEventListener("keydown",this.#o,n),document.addEventListener("keyup",this.#o,n);const i=o.drawFrontCanvas.bind(o);e.addEventListener("abort",()=>{o.drawFrontCanvas=i}),o.drawFrontCanvas=()=>{i(),this.draw()}}#e=this.onPointerDownOrMove.bind(this);onPointerDownOrMove(o){this.mouse0Down=(o.buttons&1)===1,this.mouse1Down=(o.buttons&4)===4,this.mouse2Down=(o.buttons&2)===2,this.x=o.clientX,this.y=o.clientY,this.canvas.setDirty(!0)}#t=this.onPointerUp.bind(this);onPointerUp(){this.mouse0Down=!1,this.mouse1Down=!1,this.mouse2Down=!1}#o=this.onKeyDownOrUp.bind(this);onKeyDownOrUp(o){this.ctrlDown=o.ctrlKey,this.altDown=o.altKey,this.shiftDown=o.shiftKey,this.undoDown=o.ctrlKey&&o.code==="KeyZ"&&o.type==="keydown",this.redoDown=o.ctrlKey&&o.code==="KeyY"&&o.type==="keydown"}draw(){const{canvas:{ctx:o},radius:e,startAngle:t,endAngle:n,x:i,y:s,inactiveColour:a,colour1:r,colour2:l,colour3:d,fontString:u}=this,{fillStyle:p,font:m}=o,g=i,f=s-80,y=g,b=f-15;o.font=u,S(y+0,b,"Shift",this.shiftDown?r:a),S(y+45,b+20,"Alt",this.altDown?l:a),S(y+30,b,"Control",this.ctrlDown?d:a),S(y-30,b,"↩️",this.undoDown?"#000":"transparent"),S(y+45,b,"↪️",this.redoDown?"#000":"transparent"),o.beginPath(),C(g,f),C(g+15,f),C(g+30,f),o.fillStyle=a,o.fill();const v=this.mouse0Down?r:a,k=this.mouse1Down?l:a,w=this.mouse2Down?d:a;this.mouse0Down&&E(g,f,v),this.mouse1Down&&E(g+15,f,k),this.mouse2Down&&E(g+30,f,w),o.fillStyle=p,o.font=m;function S(I,P,A,F){o.fillStyle=F,o.fillText(A,I,P)}h(S,"textMarker");function E(I,P,A){o.beginPath(),o.fillStyle=A,C(I,P),o.fill()}h(E,"mouseMarker");function C(I,P){o.arc(I,P,e,t,n)}h(C,"drawDot")}dispose(){this.controller?.abort(),this.controller=void 0}[Symbol.dispose](){this.dispose()}},Ww=class{static{h(this,"LiteGraphGlobal")}SlotShape=Ne;SlotDirection=ws;SlotType=pt;LabelPosition=tt;VERSION=.4;CANVAS_GRID_SIZE=10;NODE_TITLE_HEIGHT=30;NODE_TITLE_TEXT_Y=20;NODE_SLOT_HEIGHT=20;NODE_WIDGET_HEIGHT=20;NODE_WIDTH=140;NODE_MIN_WIDTH=50;NODE_COLLAPSED_RADIUS=10;NODE_COLLAPSED_WIDTH=80;NODE_TITLE_COLOR="#999";NODE_SELECTED_TITLE_COLOR="#FFF";NODE_TEXT_SIZE=14;NODE_TEXT_COLOR="#AAA";NODE_TEXT_HIGHLIGHT_COLOR="#EEE";NODE_SUBTEXT_SIZE=12;NODE_DEFAULT_COLOR="#333";NODE_DEFAULT_BGCOLOR="#353535";NODE_DEFAULT_BOXCOLOR="#666";NODE_DEFAULT_SHAPE=M.ROUND;NODE_BOX_OUTLINE_COLOR="#FFF";NODE_ERROR_COLOUR="#E00";NODE_FONT="Inter";NODE_DEFAULT_BYPASS_COLOR="#FF00FF";NODE_OPACITY=.9;DEFAULT_FONT="Inter";DEFAULT_SHADOW_COLOR="rgba(0,0,0,0.5)";DEFAULT_GROUP_FONT=24;DEFAULT_GROUP_FONT_SIZE=24;GROUP_FONT="Inter";WIDGET_BGCOLOR="#222";WIDGET_OUTLINE_COLOR="#666";WIDGET_PROMOTED_OUTLINE_COLOR="#BF00FF";WIDGET_ADVANCED_OUTLINE_COLOR="rgba(56, 139, 253, 0.8)";WIDGET_TEXT_COLOR="#DDD";WIDGET_SECONDARY_TEXT_COLOR="#999";WIDGET_DISABLED_TEXT_COLOR="#666";LINK_COLOR="#9A9";EVENT_LINK_COLOR="#A86";CONNECTING_LINK_COLOR="#AFA";MAX_NUMBER_OF_NODES=1e4;DEFAULT_POSITION=[100,100];VALID_SHAPES=["default","box","round","card"];ROUND_RADIUS=8;BOX_SHAPE=M.BOX;ROUND_SHAPE=M.ROUND;CIRCLE_SHAPE=M.CIRCLE;CARD_SHAPE=M.CARD;ARROW_SHAPE=M.ARROW;GRID_SHAPE=M.GRID;INPUT=j.INPUT;OUTPUT=j.OUTPUT;EVENT=-1;ACTION=-1;NODE_MODES=["Always","On Event","Never","On Trigger"];NODE_MODES_COLORS=["#666","#422","#333","#224","#626"];ALWAYS=H.ALWAYS;ON_EVENT=H.ON_EVENT;NEVER=H.NEVER;ON_TRIGGER=H.ON_TRIGGER;UP=O.UP;DOWN=O.DOWN;LEFT=O.LEFT;RIGHT=O.RIGHT;CENTER=O.CENTER;LINK_RENDER_MODES=["Straight","Linear","Spline"];HIDDEN_LINK=ie.HIDDEN_LINK;STRAIGHT_LINK=ie.STRAIGHT_LINK;LINEAR_LINK=ie.LINEAR_LINK;SPLINE_LINK=ie.SPLINE_LINK;NORMAL_TITLE=se.NORMAL_TITLE;NO_TITLE=se.NO_TITLE;TRANSPARENT_TITLE=se.TRANSPARENT_TITLE;AUTOHIDE_TITLE=se.AUTOHIDE_TITLE;VERTICAL_LAYOUT="vertical";proxy=null;node_images_path="";debug=!1;catch_exceptions=!0;throw_errors=!0;allow_scripts=!1;registered_node_types={};node_types_by_file_extension={};Nodes={};Globals={};searchbox_extras={};node_box_coloured_when_on=!1;node_box_coloured_by_mode=!1;dialog_close_on_mouse_leave=!1;dialog_close_on_mouse_leave_delay=500;shift_click_do_break_link_from=!1;click_do_break_link_to=!1;ctrl_alt_click_do_break_link=!0;snaps_for_comfy=!0;snap_highlights_node=!0;alwaysSnapToGrid;snapToGrid;search_hide_on_mouse_leave=!0;search_filter_enabled=!1;search_show_all_on_open=!0;auto_load_slot_types=!1;registered_slot_in_types={};registered_slot_out_types={};slot_types_in=[];slot_types_out=[];slot_types_default_in={};slot_types_default_out={};alt_drag_do_clone_nodes=!1;do_add_triggers_slots=!1;allow_multi_output_for_events=!0;middle_click_slot_add_default_node=!1;release_link_on_empty_shows_menu=!1;pointerevents_method="pointer";ctrl_shift_v_paste_connect_unselected_outputs=!0;use_uuids=!1;highlight_selected_group=!0;context_menu_scaling=!1;alwaysRepeatWarnings=!1;onDeprecationWarning=[console.warn];macTrackpadGestures=!1;macGesturesRequireMac=!0;canvasNavigationMode="legacy";leftMouseClickBehavior="panning";mouseWheelScroll="panning";truncateWidgetTextEvenly=!1;truncateWidgetValuesFirst=!1;saveViewportWithGraph=!0;vueNodesMode=!1;nodeOpacity=1;nodeLightness=void 0;LGraph=Zt;LLink=z;LGraphNode=q;LGraphGroup=de;DragAndScale=tn;LGraphCanvas=ce;ContextMenu=zi;CurveEditor=ji;Reroute=J;constructor(){Object.defineProperty(this,"Classes",{writable:!1})}Classes={get SubgraphSlot(){return so},get SubgraphIONodeBase(){return _e},get Rectangle(){return X},get InputIndicators(){return Uw}};registerNodeType(o,e){if(!e.prototype)throw"Cannot register a simple object, it must be a class with a prototype";e.type=o;const t=e.name,n=o.lastIndexOf("/");e.category=o.substring(0,n),e.title||=t;for(const s in q.prototype)e.prototype[s]||=q.prototype[s];const i=this.registered_node_types[o];i&&this.debug&&console.warn("replacing node type:",o),this.registered_node_types[o]=e,e.constructor.name&&(this.Nodes[t]=e),this.onNodeTypeRegistered?.(o,e),i&&this.onNodeTypeReplaced?.(o,e,i),e.prototype.onPropertyChange&&console.warn(`LiteGraph node class ${o} has onPropertyChange method, it must be called onPropertyChanged with d at the end`),this.auto_load_slot_types&&new e(e.title||"tmpnode")}unregisterNodeType(o){const e=typeof o=="string"?this.registered_node_types[o]:o;if(!e)throw`node type not found: ${String(o)}`;delete this.registered_node_types[String(e.type)];const t=e.constructor.name;t&&delete this.Nodes[t]}registerNodeAndSlotType(o,e,t){t||=!1;const n=(typeof o=="string"&&this.registered_node_types[o]!=="anonymous"?this.registered_node_types[o]:o).constructor.type;let i=[];typeof e=="string"?i=e.split(","):e==this.EVENT||e==this.ACTION?i=["_event_"]:i=["*"];for(let s of i){s===""&&(s="*");const a=t?this.registered_slot_out_types:this.registered_slot_in_types;a[s]??={nodes:[]};const{nodes:r}=a[s];r.includes(n)||r.push(n);const l=t?this.slot_types_out:this.slot_types_in,d=s.toLowerCase();l.includes(d)||(l.push(d),l.sort())}}clearRegisteredTypes(){this.registered_node_types={},this.node_types_by_file_extension={},this.Nodes={},this.searchbox_extras={}}createNode(o,e,t){const n=this.registered_node_types[o];if(!n)return this.debug&&console.warn(`GraphNode type "${o}" not registered.`),null;e=e||n.title||o;let i=null;if(this.catch_exceptions)try{i=new n(e)}catch(s){return console.error(s),null}else i=new n(e);if(i.type=o,!i.title&&e&&(i.title=e),i.properties||={},i.properties_info||=[],i.flags||={},i.size||=i.computeSize(),i.pos||=[this.DEFAULT_POSITION[0],this.DEFAULT_POSITION[1]],i.mode||=H.ALWAYS,t)for(const s in t)i[s]=t[s];return i.onNodeCreated?.(),i}getNodeType(o){return this.registered_node_types[o]}getNodeTypesInCategory(o,e){const t=[];for(const n in this.registered_node_types){const i=this.registered_node_types[n];i.filter==e&&(o==""?i.category==null&&t.push(i):i.category==o&&t.push(i))}return t}getNodeTypesCategories(o){const e={"":1};for(const n in this.registered_node_types){const i=this.registered_node_types[n];if(i.category&&!i.skip_list){if(i.filter!=o)continue;e[i.category]=1}}const t=[];for(const n in e)t.push(n);return t}reloadNodes(o){const e=document.getElementsByTagName("script"),t=[];for(const i of e)t.push(i);const n=document.getElementsByTagName("head")[0];o=document.location.href+o;for(const i of t){const s=i.src;if(!(!s||s.substr(0,o.length)!=o))try{const a=document.createElement("script");a.type="text/javascript",a.src=s,n.append(a),i.remove()}catch(a){if(this.throw_errors)throw a;this.debug&&console.error("Error while reloading",s)}}}cloneObject(o,e){if(o==null)return null;const t=JSON.parse(JSON.stringify(o));if(!e)return t;for(const n in t)e[n]=t[n];return e}uuidv4=fe;isValidConnection(o,e){if((o==""||o==="*")&&(o=0),(e==""||e==="*")&&(e=0),!o||!e||o==e||o==this.EVENT&&e==this.ACTION)return!0;if(o=String(o),e=String(e),o=o.toLowerCase(),e=e.toLowerCase(),!o.includes(",")&&!e.includes(","))return o==e;const t=o.split(","),n=e.split(",");for(const i of t)for(const s of n)if(this.isValidConnection(i,s))return!0;return!1}getParameterNames(o){return String(o).replaceAll(/\/\/.*$/gm,"").replaceAll(/\s+/g,"").replaceAll(/\/\*[^*/]*\*\//g,"").split("){",1)[0].replace(/^[^(]*\(/,"").replaceAll(/=[^,]+/g,"").split(",").filter(Boolean)}pointerListenerAdd(o,e,t,n=!1){if(!o||!o.addEventListener||!e||typeof t!="function")return;let i=this.pointerevents_method,s=e;if(i=="pointer"&&!window.PointerEvent)switch(console.warn("sMethod=='pointer' && !window.PointerEvent"),console.warn(`Converting pointer[${s}] : down move up cancel enter TO touchstart touchmove touchend, etc ..`),s){case"down":i="touch",s="start";break;case"move":i="touch";break;case"up":i="touch",s="end";break;case"cancel":i="touch";break;case"enter":break;default:console.warn(`PointerEvent not available in this browser ? The event ${s} would not be called`)}switch(s){case"down":case"up":case"move":case"over":case"out":case"enter":o.addEventListener(i+s,t,n);case"leave":case"cancel":case"gotpointercapture":case"lostpointercapture":if(i!="mouse")return o.addEventListener(i+s,t,n);default:return o.addEventListener(s,t,n)}}pointerListenerRemove(o,e,t,n=!1){if(!(!o||!o.removeEventListener||!e||typeof t!="function"))switch(e){case"down":case"up":case"move":case"over":case"out":case"enter":(this.pointerevents_method=="pointer"||this.pointerevents_method=="mouse")&&o.removeEventListener(this.pointerevents_method+e,t,n);case"leave":case"cancel":case"gotpointercapture":case"lostpointercapture":if(this.pointerevents_method=="pointer")return o.removeEventListener(this.pointerevents_method+e,t,n);default:return o.removeEventListener(e,t,n)}}getTime(){return performance.now()}distance=Ue;colorToString(o){return`rgba(${Math.round(o[0]*255).toFixed()},${Math.round(o[1]*255).toFixed()},${Math.round(o[2]*255).toFixed()},${o.length==4?o[3].toFixed(2):"1.0"})`}isInsideRectangle=Ui;growBounding(o,e,t){e<o[0]?o[0]=e:e>o[2]&&(o[2]=e),t<o[1]?o[1]=t:t>o[3]&&(o[3]=t)}overlapBounding=Le;isInsideBounding(o,e){return!(o[0]<e[0][0]||o[1]<e[0][1]||o[0]>e[1][0]||o[1]>e[1][1])}hex2num(o){o.charAt(0)=="#"&&(o=o.slice(1)),o=o.toUpperCase();const e="0123456789ABCDEF",t=new Array(3);let n=0,i,s;for(let a=0;a<6;a+=2)i=e.indexOf(o.charAt(a)),s=e.indexOf(o.charAt(a+1)),t[n]=i*16+s,n++;return t}num2hex(o){const e="0123456789ABCDEF";let t="#",n,i;for(let s=0;s<3;s++)n=o[s]/16,i=o[s]%16,t+=e.charAt(n)+e.charAt(i);return t}closeAllContextMenus(o=window){const e=[...o.document.querySelectorAll(".litecontextmenu")];if(e.length)for(const t of e)"close"in t&&typeof t.close=="function"?t.close():t.remove()}extendClass(o,e){for(const t in e)o.hasOwnProperty(t)||(o[t]=e[t]);if(e.prototype&&o.prototype){const t=e.prototype,n=o.prototype;for(const i in t){if(!t.hasOwnProperty(i)||n.hasOwnProperty(i))continue;const s=Object.getOwnPropertyDescriptor(t,i);s&&Object.defineProperty(n,i,s)}}}};Symbol.dispose??=Symbol("Symbol.dispose");Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");function Gw(){typeof window<"u"&&window.CanvasRenderingContext2D&&!window.CanvasRenderingContext2D.prototype.roundRect&&(window.CanvasRenderingContext2D.prototype.roundRect=function(o,e,t,n,i,s){let a=0,r=0,l=0,d=0;if(i===0){this.rect(o,e,t,n);return}if(s===void 0&&(s=i),Array.isArray(i))if(i.length==1)a=r=l=d=i[0];else if(i.length==2)a=d=i[0],r=l=i[1];else if(i.length==4)a=i[0],r=i[1],l=i[2],d=i[3];else return;else{a=i||0,r=i||0;const u=!Array.isArray(s)&&s?s:0;l=u,d=u}this.moveTo(o+a,e),this.lineTo(o+t-r,e),this.quadraticCurveTo(o+t,e,o+t,e+r),this.lineTo(o+t,e+n-d),this.quadraticCurveTo(o+t,e+n,o+t-d,e+n),this.lineTo(o+d,e+n),this.quadraticCurveTo(o,e+n,o,e+n-l),this.lineTo(o,e+l),this.quadraticCurveTo(o,e,o+a,e)}),typeof window<"u"&&!window.requestAnimationFrame&&(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(o){window.setTimeout(o,1e3/60)})}h(Gw,"loadPolyfills");const _=new Ww;Gw();var Pn=c.object({CLIP:c.string(),CLIP_VISION:c.string(),CLIP_VISION_OUTPUT:c.string(),CONDITIONING:c.string(),CONTROL_NET:c.string(),IMAGE:c.string(),LATENT:c.string(),MASK:c.string(),MODEL:c.string(),STYLE_MODEL:c.string(),VAE:c.string(),NOISE:c.string(),GUIDER:c.string(),SAMPLER:c.string(),SIGMAS:c.string(),TAESD:c.string()}),Mn=c.object({BACKGROUND_IMAGE:c.string(),CLEAR_BACKGROUND_COLOR:c.string(),NODE_TITLE_COLOR:c.string(),NODE_SELECTED_TITLE_COLOR:c.string(),NODE_TEXT_SIZE:c.number(),NODE_TEXT_COLOR:c.string(),NODE_TEXT_HIGHLIGHT_COLOR:c.string(),NODE_SUBTEXT_SIZE:c.number(),NODE_DEFAULT_COLOR:c.string(),NODE_DEFAULT_BGCOLOR:c.string(),NODE_DEFAULT_BOXCOLOR:c.string(),NODE_DEFAULT_SHAPE:c.union([c.literal(_.BOX_SHAPE),c.literal(_.ROUND_SHAPE),c.literal(_.CARD_SHAPE),c.string()]),NODE_BOX_OUTLINE_COLOR:c.string(),NODE_BYPASS_BGCOLOR:c.string(),NODE_ERROR_COLOUR:c.string(),DEFAULT_SHADOW_COLOR:c.string(),DEFAULT_GROUP_FONT:c.number(),WIDGET_BGCOLOR:c.string(),WIDGET_OUTLINE_COLOR:c.string(),WIDGET_TEXT_COLOR:c.string(),WIDGET_SECONDARY_TEXT_COLOR:c.string(),WIDGET_DISABLED_TEXT_COLOR:c.string(),LINK_COLOR:c.string(),EVENT_LINK_COLOR:c.string(),CONNECTING_LINK_COLOR:c.string(),BADGE_FG_COLOR:c.string(),BADGE_BG_COLOR:c.string()});const Rn=c.object({"fg-color":c.string(),"bg-color":c.string(),"bg-img":c.string().optional(),"comfy-menu-bg":c.string(),"comfy-menu-secondary-bg":c.string(),"comfy-input-bg":c.string(),"input-text":c.string(),"descrip-text":c.string(),"drag-text":c.string(),"error-text":c.string(),"border-color":c.string(),"tr-even-bg-color":c.string(),"tr-odd-bg-color":c.string(),"content-bg":c.string(),"content-fg":c.string(),"content-hover-bg":c.string(),"content-hover-fg":c.string(),"bar-shadow":c.string(),"contrast-mix-color":c.string().optional(),"interface-stroke":c.string().optional(),"interface-panel-surface":c.string().optional(),"interface-panel-box-shadow":c.string().optional(),"interface-panel-drop-shadow":c.string().optional(),"interface-panel-hover-surface":c.string().optional(),"interface-panel-selected-surface":c.string().optional(),"interface-button-hover-surface":c.string().optional()});var Hw=c.object({node_slot:Pn,litegraph_base:Mn,comfy_base:Rn}),jw=c.object({node_slot:Pn.partial(),litegraph_base:Mn.partial(),comfy_base:Rn.partial()});const qw=c.object({id:c.string(),name:c.string(),colors:jw,light_theme:c.boolean().optional()}).passthrough();c.object({id:c.string(),name:c.string(),colors:Hw}).passthrough();const $w=c.record(qw);var Kw=c.object({key:c.string(),ctrl:c.boolean().optional(),alt:c.boolean().optional(),shift:c.boolean().optional(),meta:c.boolean().optional()});const Ro=c.object({commandId:c.string(),combo:Kw,targetElementId:c.string().optional()});let ft=(function(o){return o.Core="core",o.CustomNodes="custom_nodes",o.Blueprint="blueprint",o.Unknown="unknown",o})({});var Fo={type:ft.Unknown,className:"comfy-unknown",displayText:"Unknown",badgeText:"?"},Xw=h(o=>o.replace(/^(ComfyUI-|ComfyUI_|Comfy-|Comfy_)/,"").replace(/(-ComfyUI|_ComfyUI|-Comfy|_Comfy)$/,""),"shortenNodeName");const oI=h(o=>{if(!o)return Fo;const e=o.split(".");if(["nodes","comfy_extras","comfy_api_nodes"].includes(e[0]))return{type:ft.Core,className:"comfy-core",displayText:"Comfy Core",badgeText:"🦊"};if(e[0]==="blueprint")return{type:ft.Blueprint,className:"blueprint",displayText:"Blueprint",badgeText:"bp"};if(e[0]==="custom_nodes"){const t=e[1].split("@")[0],n=Xw(t);return{type:ft.CustomNodes,className:"comfy-custom-nodes",displayText:n,badgeText:n}}else return Fo},"getNodeSource");let Yw=(function(o){return o.None="None",o.ShowAll="Show all",o.HideBuiltIn="Hide built-in",o})({}),Qw=(function(o){return o.CONTEXT_MENU="context menu",o.SEARCH_BOX="search box",o.NO_ACTION="no action",o})({});var Fn=c.string(),ot=c.string();const zn=c.enum(["input","output","temp"]);var Ht=c.object({filename:c.string().optional(),subfolder:c.string().optional(),type:zn.optional()}),Bn=c.object({audio:c.array(Ht).optional(),images:c.array(Ht).optional(),video:c.array(Ht).optional(),animated:c.array(c.boolean()).optional(),text:c.union([c.string(),c.array(c.string())]).optional()}).passthrough(),Zw=c.object({exec_info:c.object({queue_remaining:c.number().int()})});c.object({status:Zw.nullish(),sid:c.string().nullish()});c.object({value:c.number().int(),max:c.number().int(),prompt_id:ot,node:W});var Jw=c.object({value:c.number(),max:c.number(),state:c.enum(["pending","running","finished","error"]),node_id:W,prompt_id:ot,display_node_id:W.optional(),parent_node_id:W.optional(),real_node_id:W.optional()});c.object({prompt_id:ot,nodes:c.record(W,Jw)});c.object({node:W,display_node:W,prompt_id:ot}).extend({output:Bn,merge:c.boolean().optional()});var ao=c.object({prompt_id:ot,timestamp:c.number().int()});ao.extend({nodes:c.array(W)});ao.extend({node_id:W,node_type:Fn,executed:c.array(W)});ao.extend({node_id:W,node_type:Fn,executed:c.array(W),exception_message:c.string(),exception_type:c.string(),traceback:c.array(c.string()),current_inputs:c.any(),current_outputs:c.any()});c.object({nodeId:W,text:c.string()});c.object({value:c.string(),id:c.string().optional()});var Vn=c.object({cols:c.number(),row:c.number()}),Un=c.object({t:c.string(),m:c.string()});c.object({size:Vn.optional(),entries:c.array(Un)});c.object({size:Vn,entries:c.array(Un)});c.record(c.string(),c.any());c.object({task_id:c.string(),asset_name:c.string(),bytes_total:c.number(),bytes_downloaded:c.number(),progress:c.number(),status:c.enum(["created","running","completed","failed"]),asset_id:c.string().optional(),error:c.string().optional()});const eS=c.record(W,Bn);c.array(c.string());c.array(c.string());var Wn=c.object({type:c.string(),message:c.string(),details:c.string(),extra_info:c.object({input_name:c.string().optional()}).passthrough().optional()}),tS=c.object({errors:c.array(Wn),class_type:c.string(),dependent_outputs:c.array(c.any())});c.object({node_errors:c.record(W,tS).optional(),prompt_id:c.string().optional(),exec_info:c.object({queue_remaining:c.number().optional()}).optional(),error:c.union([c.string(),Wn])});var oS=c.object({name:c.string(),type:c.string(),index:c.number(),vram_total:c.number(),vram_free:c.number(),torch_vram_total:c.number(),torch_vram_free:c.number()});c.object({system:c.object({os:c.string(),python_version:c.string(),embedded_python:c.boolean(),comfyui_version:c.string(),pytorch_version:c.string(),required_frontend_version:c.string().optional(),argv:c.array(c.string()),ram_total:c.number(),ram_free:c.number(),cloud_version:c.string().optional(),comfyui_frontend_version:c.string().optional(),workflow_templates_version:c.string().optional()}),devices:c.array(oS)});c.object({storage:c.enum(["server"]),migrated:c.boolean().optional(),users:c.record(c.string(),c.string()).optional()});c.array(c.array(c.string(),c.string()));c.object({path:c.string(),size:c.number(),modified:c.number()});var nS=c.object({icon:c.string().optional(),color:c.string().optional()}),zo=c.enum(Object.values(Qw)),jt=c.enum(Object.values(Yw)),iS=c.enum(["default","none","auto","latent2rgb","taesd"]);c.object({"Comfy.ColorPalette":c.string(),"Comfy.CustomColorPalettes":$w,"Comfy.Canvas.BackgroundImage":c.string().optional(),"Comfy.ConfirmClear":c.boolean(),"Comfy.DevMode":c.boolean(),"Comfy.UI.TabBarLayout":c.enum(["Default","Integrated"]),"Comfy.Workflow.ShowMissingNodesWarning":c.boolean(),"Comfy.Workflow.ShowMissingModelsWarning":c.boolean(),"Comfy.Workflow.WarnBlueprintOverwrite":c.boolean(),"Comfy.DisableFloatRounding":c.boolean(),"Comfy.DisableSliders":c.boolean(),"Comfy.DOMClippingEnabled":c.boolean(),"Comfy.EditAttention.Delta":c.number(),"Comfy.EnableTooltips":c.boolean(),"Comfy.EnableWorkflowViewRestore":c.boolean(),"Comfy.FloatRoundingPrecision":c.number(),"Comfy.Graph.CanvasInfo":c.boolean(),"Comfy.Graph.CanvasMenu":c.boolean(),"Comfy.Graph.CtrlShiftZoom":c.boolean(),"Comfy.Graph.LiveSelection":c.boolean(),"Comfy.Graph.LinkMarkers":c.nativeEnum(re),"Comfy.Graph.ZoomSpeed":c.number(),"Comfy.Group.DoubleClickTitleToEdit":c.boolean(),"Comfy.GroupSelectedNodes.Padding":c.number(),"Comfy.Locale":c.string(),"Comfy.NodeLibrary.Bookmarks":c.array(c.string()),"Comfy.NodeLibrary.Bookmarks.V2":c.array(c.string()),"Comfy.NodeLibrary.BookmarksCustomization":c.record(c.string(),nS),"Comfy.LinkRelease.Action":zo,"Comfy.LinkRelease.ActionShift":zo,"Comfy.ModelLibrary.AutoLoadAll":c.boolean(),"Comfy.ModelLibrary.NameFormat":c.enum(["filename","title"]),"Comfy.NodeSearchBoxImpl.NodePreview":c.boolean(),"Comfy.NodeSearchBoxImpl":c.enum(["default","simple"]),"Comfy.NodeSearchBoxImpl.ShowCategory":c.boolean(),"Comfy.NodeSearchBoxImpl.ShowIdName":c.boolean(),"Comfy.NodeSearchBoxImpl.ShowNodeFrequency":c.boolean(),"Comfy.NodeSuggestions.number":c.number(),"Comfy.Node.BypassAllLinksOnDelete":c.boolean(),"Comfy.Node.Opacity":c.number(),"Comfy.Node.MiddleClickRerouteNode":c.boolean(),"Comfy.Node.ShowDeprecated":c.boolean(),"Comfy.Node.ShowExperimental":c.boolean(),"Comfy.Pointer.ClickBufferTime":c.number(),"Comfy.Pointer.ClickDrift":c.number(),"Comfy.Pointer.DoubleClickTime":c.number(),"Comfy.PreviewFormat":c.string(),"Comfy.PromptFilename":c.boolean(),"Comfy.Sidebar.Location":c.enum(["left","right"]),"Comfy.Sidebar.Size":c.enum(["small","normal"]),"Comfy.Sidebar.UnifiedWidth":c.boolean(),"Comfy.Sidebar.Style":c.enum(["floating","connected"]),"Comfy.SnapToGrid.GridSize":c.number(),"Comfy.TextareaWidget.FontSize":c.number(),"Comfy.TextareaWidget.Spellcheck":c.boolean(),"Comfy.UseNewMenu":c.enum(["Disabled","Top"]),"Comfy.TreeExplorer.ItemPadding":c.number(),"Comfy.Validation.Workflows":c.boolean(),"Comfy.Workflow.SortNodeIdOnSave":c.boolean(),"Comfy.Execution.PreviewMethod":iS,"Comfy.Workflow.WorkflowTabsPosition":c.enum(["Sidebar","Topbar"]),"Comfy.Node.DoubleClickTitleToEdit":c.boolean(),"Comfy.WidgetControlMode":c.enum(["before","after"]),"Comfy.Window.UnloadConfirmation":c.boolean(),"Comfy.NodeBadge.NodeSourceBadgeMode":jt,"Comfy.NodeBadge.NodeIdBadgeMode":jt,"Comfy.NodeBadge.NodeLifeCycleBadgeMode":jt,"Comfy.NodeBadge.ShowApiPricing":c.boolean(),"Comfy.Notification.ShowVersionUpdates":c.boolean(),"Comfy.QueueButton.BatchCountLimit":c.number(),"Comfy.Queue.MaxHistoryItems":c.number(),"Comfy.Queue.History.Expanded":c.boolean(),"Comfy.Keybinding.UnsetBindings":c.array(Ro),"Comfy.Keybinding.NewBindings":c.array(Ro),"Comfy.Extension.Disabled":c.array(c.string()),"Comfy.LinkRenderMode":c.number(),"Comfy.Node.AutoSnapLinkToSlot":c.boolean(),"Comfy.Node.SnapHighlightsNode":c.boolean(),"Comfy.Server.ServerConfigValues":c.record(c.string(),c.any()),"Comfy.Server.LaunchArgs":c.record(c.string(),c.string()),"LiteGraph.Canvas.MaximumFps":c.number(),"Comfy.Workflow.ConfirmDelete":c.boolean(),"Comfy.Workflow.AutoSaveDelay":c.number(),"Comfy.Workflow.AutoSave":c.enum(["off","after delay"]),"Comfy.RerouteBeta":c.boolean(),"LiteGraph.Canvas.MinFontSizeForLOD":c.number(),"Comfy.Canvas.SelectionToolbox":c.boolean(),"LiteGraph.Node.TooltipDelay":c.number(),"LiteGraph.ContextMenu.Scaling":c.boolean(),"LiteGraph.Reroute.SplineOffset":c.number(),"LiteGraph.Canvas.LowQualityRenderingZoomThreshold":c.number(),"Comfy.Toast.DisableReconnectingToast":c.boolean(),"Comfy.Workflow.Persist":c.boolean(),"Comfy.TutorialCompleted":c.boolean(),"Comfy.InstalledVersion":c.string().nullable(),"Comfy.Node.AllowImageSizeDraw":c.boolean(),"Comfy.Minimap.Visible":c.boolean(),"Comfy.Minimap.NodeColors":c.boolean(),"Comfy.Minimap.ShowLinks":c.boolean(),"Comfy.Minimap.ShowGroups":c.boolean(),"Comfy.Minimap.RenderBypassState":c.boolean(),"Comfy.Minimap.RenderErrorState":c.boolean(),"Comfy.Canvas.NavigationMode":c.string(),"Comfy.Canvas.LeftMouseClickBehavior":c.string(),"Comfy.Canvas.MouseWheelScroll":c.string(),"Comfy.VueNodes.Enabled":c.boolean(),"Comfy.VueNodes.AutoScaleLayout":c.boolean(),"Comfy.Assets.UseAssetAPI":c.boolean(),"Comfy.Queue.QPOV2":c.boolean(),"Comfy-Desktop.AutoUpdate":c.boolean(),"Comfy-Desktop.SendStatistics":c.boolean(),"Comfy-Desktop.WindowStyle":c.string(),"Comfy-Desktop.UV.PythonInstallMirror":c.string(),"Comfy-Desktop.UV.PypiInstallMirror":c.string(),"Comfy-Desktop.UV.TorchInstallMirror":c.string(),"Comfy.MaskEditor.BrushAdjustmentSpeed":c.number(),"Comfy.MaskEditor.UseDominantAxis":c.boolean(),"Comfy.Load3D.ShowGrid":c.boolean(),"Comfy.Load3D.BackgroundColor":c.string(),"Comfy.Load3D.LightIntensity":c.number(),"Comfy.Load3D.LightIntensityMaximum":c.number(),"Comfy.Load3D.LightIntensityMinimum":c.number(),"Comfy.Load3D.LightAdjustmentIncrement":c.number(),"Comfy.Load3D.CameraType":c.enum(["perspective","orthographic"]),"Comfy.Load3D.3DViewerEnable":c.boolean(),"Comfy.Load3D.PLYEngine":c.enum(["threejs","fastply","sparkjs"]),"Comfy.Memory.AllowManualUnload":c.boolean(),"pysssss.SnapToGrid":c.boolean(),"VHS.AdvancedPreviews":c.string(),"Comfy.Release.Version":c.string(),"Comfy.Release.Status":c.enum(["skipped","changelog seen","what's new seen"]),"Comfy.Release.Timestamp":c.number(),"Comfy.Templates.SelectedModels":c.array(c.string()),"Comfy.Templates.SelectedUseCases":c.array(c.string()),"Comfy.Templates.SelectedRunsOn":c.array(c.string()),"Comfy.Templates.SortBy":c.enum(["default","recommended","popular","alphabetical","newest","vram-low-to-high","model-size-low-to-high"]),"test.setting":c.any(),"main.sub.setting.name":c.any(),"single.setting":c.any(),"LiteGraph.Node.DefaultPadding":c.boolean(),"LiteGraph.Pointer.TrackpadGestures":c.boolean(),"Comfy.VersionCompatibility.DisableWarnings":c.boolean(),"Comfy.RightSidePanel.IsOpen":c.boolean()});var sS=c.enum(["pending","in_progress","completed","failed","cancelled"]),aS=c.object({filename:c.string(),subfolder:c.string(),type:zn,nodeId:c.string(),mediaType:c.string()}),rS=c.object({prompt_id:c.string().optional(),timestamp:c.number().optional(),node_id:c.string(),node_type:c.string(),executed:c.array(c.string()).optional(),exception_message:c.string(),exception_type:c.string(),traceback:c.array(c.string()),current_inputs:c.unknown(),current_outputs:c.unknown()}).passthrough(),Gn=c.object({id:c.string(),status:sS,create_time:c.number(),execution_start_time:c.number().nullable().optional(),execution_end_time:c.number().nullable().optional(),preview_output:aS.nullable().optional(),outputs_count:c.number().nullable().optional(),execution_error:rS.nullable().optional(),workflow_id:c.string().nullable().optional(),priority:c.number().optional()}).passthrough();const lS=Gn.extend({workflow:c.unknown().optional(),outputs:eS.optional(),update_time:c.number().optional(),execution_status:c.unknown().optional(),execution_meta:c.unknown().optional()}).passthrough();var dS=c.object({offset:c.number(),limit:c.number(),total:c.number(),has_more:c.boolean()});const uS=c.object({jobs:c.array(Gn),pagination:dS}),cS=c.object({extra_data:c.object({extra_pnginfo:c.object({workflow:c.unknown()}).optional()}).optional()});async function Hn(o,e,t=200,n=0){const i=`/jobs?status=${e.join(",")}&limit=${t}&offset=${n}`;try{const s=await o(i);if(!s.ok)return console.error(`[Jobs API] Failed to fetch jobs: ${s.status}`),{jobs:[],total:0,offset:0};const a=uS.parse(await s.json());return{jobs:a.jobs,total:a.pagination.total,offset:n}}catch(s){return console.error("[Jobs API] Error fetching jobs:",s),{jobs:[],total:0,offset:0}}}h(Hn,"fetchJobsRaw");var Bo=1e6;function Jt(o,e){return o.map((t,n)=>({...t,priority:t.priority??e-n}))}h(Jt,"assignPriority");async function pS(o,e=200,t=0){const{jobs:n,total:i}=await Hn(o,["completed","failed","cancelled"],e,t);return Jt(n,i-t)}h(pS,"fetchHistory");async function mS(o){const{jobs:e}=await Hn(o,["in_progress","pending"],200,0),t=e.filter(i=>i.status==="in_progress"),n=e.filter(i=>i.status==="pending");return{Running:Jt(t,Bo+t.length),Pending:Jt(n,Bo+t.length+n.length)}}h(mS,"fetchQueue");async function hS(o,e){try{const t=await o(`/jobs/${encodeURIComponent(e)}`);if(!t.ok){console.warn(`Job not found for prompt ${e}`);return}return lS.parse(await t.json())}catch(t){console.error(`Failed to fetch job detail for prompt ${e}:`,t);return}}h(hS,"fetchJobDetail");async function nI(o){const e=cS.safeParse(o?.workflow);if(!e.success)return;const t=e.data.extra_data?.extra_pnginfo?.workflow;if(t)return await Mi(t,n=>{console.warn("[extractWorkflow] Workflow validation failed:",n)})??void 0}h(nI,"extractWorkflow");var jn=class extends Error{static{h(this,"UnauthorizedError")}};function Vo(o,e,t){Array.isArray(o)?o.push([e,t]):o instanceof Headers?o.set(e,t):o[e]=t}h(Vo,"addHeaderEntry");var qn=class extends Error{static{h(this,"PromptExecutionError")}response;constructor(o){super("Prompt execution failed"),this.response=o}toString(){let o="";typeof this.response.error=="string"?o+=this.response.error:this.response.error&&(o+=this.response.error.message+": "+this.response.error.details);for(const[e,t]of Object.entries(this.response.node_errors??[])){o+=`
|
|
77
77
|
`+t.class_type+":";for(const n of t.errors)o+=`
|
|
78
|
-
- `+n.message+": "+n.details}return o}},$n=class extends EventTarget{static{h(this,"ComfyApi")}#e=new Set;api_host;api_base;initialClientId;clientId;user;socket=null;authStoreComposable;reportedUnknownMessageTypes=new Set;getClientFeatureFlags(){return{...ci}}serverFeatureFlags={};authToken;apiKey;constructor(){super(),this.user="",this.api_host=location.host,this.api_base=ke?"":location.pathname.split("/").slice(0,-1).join("/"),this.initialClientId=sessionStorage.getItem("clientId")}internalURL(o){return this.api_base+"/internal"+o}apiURL(o){return this.api_base+"/api"+o}fileURL(o){return this.api_base+o}async getAuthStore(){if(ke)return this.authStoreComposable||(this.authStoreComposable=(await R(()=>import("./firebaseAuthStore-CZgxeMyf.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]),import.meta.url)).useFirebaseAuthStore),this.authStoreComposable()}async waitForAuthInitialization(){if(ke){const o=await this.getAuthStore();if(!o||o.isInitialized)return;try{await Promise.race([Jn(o.isInitialized),oi(1e4)])}catch{console.warn("Firebase auth initialization timeout after 10 seconds")}}}async fetchApi(o,e){const t=e?.headers??{};if(ke){await this.waitForAuthInitialization();const i=await h(async()=>{try{const s=await this.getAuthStore();return s?await s.getAuthHeader():null}catch(s){return console.warn("Failed to get auth header:",s),null}},"getAuthHeaderIfAvailable")();if(i)for(const[s,a]of Object.entries(i))Vo(t,s,a)}return Vo(t,"Comfy-User",this.user),fetch(this.apiURL(o),{cache:"no-cache",...e,headers:t})}addEventListener(o,e,t){super.addEventListener(o,e,t),this.#e.add(o)}removeEventListener(o,e,t){super.removeEventListener(o,e,t)}dispatchCustomEvent(o,e){const t=e===void 0?new CustomEvent(o):new CustomEvent(o,{detail:e});return super.dispatchEvent(t)}dispatchEvent(o){return super.dispatchEvent(o)}#t(){setInterval(async()=>{try{const o=await(await this.fetchApi("/prompt")).json();this.dispatchCustomEvent("status",o)}catch{this.dispatchCustomEvent("status",null)}},1e3)}async createSocket(o){if(this.socket)return;let e=!1,t=window.name;const n=new URLSearchParams;if(t&&n.set("clientId",t),ke)try{const r=await(await this.getAuthStore())?.getIdToken();r&&n.set("token",r)}catch(r){console.warn("Could not get auth token for WebSocket connection:",r)}const i=`${window.location.protocol==="https:"?"wss":"ws"}://${this.api_host}${this.api_base}/ws`,s=n.toString(),a=s?`${i}?${s}`:i;this.socket=new WebSocket(a),this.socket.binaryType="arraybuffer",this.socket.addEventListener("open",()=>{e=!0,this.socket.send(JSON.stringify({type:"feature_flags",data:this.getClientFeatureFlags()})),o&&this.dispatchCustomEvent("reconnected")}),this.socket.addEventListener("error",()=>{this.socket&&this.socket.close(),!o&&!e&&this.#t()}),this.socket.addEventListener("close",()=>{setTimeout(async()=>{this.socket=null,await this.createSocket(!0)},300),e&&(this.dispatchCustomEvent("status",null),this.dispatchCustomEvent("reconnecting"))}),this.socket.addEventListener("message",r=>{try{if(r.data instanceof ArrayBuffer){const l=new DataView(r.data),d=l.getUint32(0);let u;switch(d){case 3:const p=new TextDecoder,m=r.data.slice(4),g=l.getUint32(4);this.dispatchCustomEvent("progress_text",{nodeId:p.decode(m.slice(4,4+g)),text:p.decode(m.slice(4+g))});break;case 1:const f=l.getUint32(4),y=r.data.slice(8);switch(f){case 2:u="image/png";break;case 1:default:u="image/jpeg";break}const b=new Blob([y],{type:u});this.dispatchCustomEvent("b_preview",b);break;case 4:const v=new TextDecoder,k=l.getUint32(4),w=r.data.slice(8,8+k),S=JSON.parse(v.decode(w)),E=r.data.slice(8+k);let C=S.image_type;const I=new Blob([E],{type:C});this.dispatchCustomEvent("b_preview_with_metadata",{blob:I,nodeId:S.node_id,displayNodeId:S.display_node_id,parentNodeId:S.parent_node_id,realNodeId:S.real_node_id,promptId:S.prompt_id}),this.dispatchCustomEvent("b_preview",I);break;default:throw new Error(`Unknown binary websocket message of type ${d}`)}}else{const l=JSON.parse(r.data);switch(l.type){case"status":if(l.data.sid){const d=l.data.sid;this.clientId=d,window.name=d,sessionStorage.setItem("clientId",d)}this.dispatchCustomEvent("status",l.data.status??null);break;case"executing":this.dispatchCustomEvent("executing",l.data.display_node||l.data.node);break;case"execution_start":case"execution_error":case"execution_interrupted":case"execution_cached":case"execution_success":case"progress":case"progress_state":case"executed":case"graphChanged":case"promptQueued":case"logs":case"b_preview":case"notification":this.dispatchCustomEvent(l.type,l.data);break;case"feature_flags":this.serverFeatureFlags=l.data,this.serverFeatureFlags;break;default:if(this.#e.has(l.type))super.dispatchEvent(new CustomEvent(l.type,{detail:l.data}));else if(!this.reportedUnknownMessageTypes.has(l.type))throw this.reportedUnknownMessageTypes.add(l.type),new Error(`Unknown message type ${l.type}`)}}}catch(l){console.warn("Unhandled message:",r.data,l)}})}init(){this.createSocket()}async getExtensions(){return await(await this.fetchApi("/extensions",{cache:"no-store"})).json()}async getWorkflowTemplates(){return await(await this.fetchApi("/workflow_templates")).json()}async getCoreWorkflowTemplates(o){const e=o&&o!=="en"?`index.${o}.json`:"index.json";try{const t=await Ce.get(this.fileURL(`/templates/${e}`));return t.headers["content-type"]?.includes("application/json")?t.data:[]}catch(t){return o&&o!=="en"?(console.warn(`Localized templates for '${o}' not found, falling back to English`),this.getCoreWorkflowTemplates()):(console.error("Error loading core workflow templates:",t),[])}}async getEmbeddings(){return await(await this.fetchApi("/embeddings",{cache:"no-store"})).json()}async getNodeDefs(){return await(await this.fetchApi("/object_info",{cache:"no-store"})).json()}async queuePrompt(o,e,t){const{output:n,workflow:i}=e,s={client_id:this.clientId??"",prompt:n,...t?.partialExecutionTargets&&{partial_execution_targets:t.partialExecutionTargets},extra_data:{auth_token_comfy_org:this.authToken,api_key_comfy_org:this.apiKey,extra_pnginfo:{workflow:i},...t?.previewMethod&&t.previewMethod!=="default"&&{preview_method:t.previewMethod}}};o===-1?s.front=!0:o!=0&&(s.number=o);const a=await this.fetchApi("/prompt",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(a.status!==200)throw new qn(await a.json());return await a.json()}async getModelFolders(){const o=await this.fetchApi("/experiment/models");if(o.status===404)return[];const e=["configs","custom_nodes"];return(await o.json()).filter(t=>!e.includes(t.name))}async getModels(o){const e=await this.fetchApi(`/experiment/models/${o}`);return e.status===404?[]:await e.json()}async viewMetadata(o,e){const t=await this.fetchApi(`/view_metadata/${o}?filename=${encodeURIComponent(e)}`),n=await t.text();if(!n)return null;try{return JSON.parse(n)}catch(i){return console.error("Error viewing metadata",t.status,t.statusText,n,i),null}}async getItems(o){return o==="queue"?this.getQueue():this.getHistory()}async getQueue(){try{return await mS(this.fetchApi.bind(this))}catch(o){return console.error("Failed to fetch queue:",o),{Running:[],Pending:[]}}}async getHistory(o=200,e){try{return await pS(this.fetchApi.bind(this),o,e?.offset)}catch(t){return console.error(t),[]}}async getJobDetail(o){return hS(this.fetchApi.bind(this),o)}async getSystemStats(){return await(await this.fetchApi("/system_stats")).json()}async#o(o,e){try{await this.fetchApi("/"+o,{method:"POST",headers:{"Content-Type":"application/json"},body:e?JSON.stringify(e):void 0})}catch(t){console.error(t)}}async deleteItem(o,e){await this.#o(o,{delete:[e]})}async clearItems(o){await this.#o(o,{clear:!0})}async interrupt(o){await this.#o("interrupt",o?{prompt_id:o}:void 0)}async getUserConfig(){return(await this.fetchApi("/users")).json()}createUser(o){return this.fetchApi("/users",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:o})})}async getSettings(){const o=await this.fetchApi("/settings");if(o.status==401)throw new jn(o.statusText);return await o.json()}async getSetting(o){return(await this.fetchApi(`/settings/${encodeURIComponent(o)}`)).json()}async storeSettings(o){return this.fetchApi("/settings",{method:"POST",body:JSON.stringify(o)})}async storeSetting(o,e){return this.fetchApi(`/settings/${encodeURIComponent(o)}`,{method:"POST",body:JSON.stringify(e)})}async getUserData(o,e){return this.fetchApi(`/userdata/${encodeURIComponent(o)}`,e)}async storeUserData(o,e,t={overwrite:!0,stringify:!0,throwOnError:!0,full_info:!1}){const n=await this.fetchApi(`/userdata/${encodeURIComponent(o)}?overwrite=${t.overwrite}&full_info=${t.full_info}`,{method:"POST",body:t?.stringify?JSON.stringify(e):e,...t});if(n.status!==200&&t.throwOnError!==!1)throw new Error(`Error storing user data file '${o}': ${n.status} ${(await n).statusText}`);return n}async deleteUserData(o){return await this.fetchApi(`/userdata/${encodeURIComponent(o)}`,{method:"DELETE"})}async moveUserData(o,e,t={overwrite:!1}){return await this.fetchApi(`/userdata/${encodeURIComponent(o)}/move/${encodeURIComponent(e)}?overwrite=${t?.overwrite}`,{method:"POST"})}async listUserDataFullInfo(o){const e=Zn(o,"/"),t=await this.fetchApi(`/userdata?dir=${encodeURIComponent(e)}&recurse=true&split=false&full_info=true`);if(t.status===404)return[];if(t.status!==200)throw new Error(`Error getting user data list '${e}': ${t.status} ${t.statusText}`);return t.json()}async getGlobalSubgraphData(o){const e=await eo.fetchApi("/global_subgraphs/"+o);return e.status!==200?"":(await e.json())?.data??""}async getGlobalSubgraphs(){const o=await eo.fetchApi("/global_subgraphs");if(o.status!==200)return{};const e=await o.json();for(const[t,n]of Object.entries(e))n.data||(n.data=this.getGlobalSubgraphData(t));return e}async getLogs(){const o=ke?this.apiURL("/logs"):this.internalURL("/logs");return(await Ce.get(o)).data}async getRawLogs(){const o=ke?this.apiURL("/logs/raw"):this.internalURL("/logs/raw");return(await Ce.get(o)).data}async subscribeLogs(o){const e=ke?this.apiURL("/logs/subscribe"):this.internalURL("/logs/subscribe");return await Ce.patch(e,{enabled:o,clientId:this.clientId})}async getFolderPaths(){const o=await Ce.get(this.internalURL("/folder_paths")).catch(()=>null);return o?o.data:{}}async freeMemory(o){try{let e="";o.freeExecutionCache?e='{"unload_models": true, "free_memory": true}':e='{"unload_models": true}',(await this.fetchApi("/free",{method:"POST",headers:{"Content-Type":"application/json"},body:e})).status===200?o.freeExecutionCache?nt().add({severity:"success",summary:"Models and Execution Cache have been cleared.",life:3e3}):nt().add({severity:"success",summary:"Models have been unloaded.",life:3e3}):nt().add({severity:"error",summary:"Unloading of models failed. Installed ComfyUI may be an outdated version.",life:5e3})}catch{nt().add({severity:"error",summary:"An error occurred while trying to unload models.",life:5e3})}}async getCustomNodesI18n(){return(await Ce.get(this.apiURL("/i18n"))).data}serverSupportsFeature(o){return lo(this.serverFeatureFlags,o)===!0}getServerFeature(o,e){return lo(this.serverFeatureFlags,o,e)}getServerFeatures(){return{...this.serverFeatureFlags}}async getFuseOptions(){try{const o=await Ce.get(this.fileURL("/templates/fuse_options.json"),{headers:{"Content-Type":"application/json"}});return o.headers["content-type"]?.includes("application/json")?o.data:null}catch(o){return console.error("Error loading fuse options:",o),null}}};const eo=new $n;window.comfyAPI=window.comfyAPI||{};window.comfyAPI.api=window.comfyAPI.api||{};window.comfyAPI.api.UnauthorizedError=jn;window.comfyAPI.api.PromptExecutionError=qn;window.comfyAPI.api.ComfyApi=$n;window.comfyAPI.api.api=eo;export{$S as $,ye as A,M as At,XS as B,Uo as Bt,Cw as C,en as Ct,YS as D,O as Dt,It as E,H as Et,ks as F,CS as Ft,Ge as G,US as H,wS as Ht,z as I,nt as It,KS as J,jS as K,So as L,ke as Lt,J as M,zi as Mt,_n as N,TS as Nt,QS as O,re as Ot,vs as P,Mi as Pt,un as Q,io as R,IS as Rt,eI as S,Gi as St,ZS as T,xe as Tt,ps as U,ms as V,SS as Vt,WS as W,GS as X,BS as Y,HS as Z,gt as _,ES as _t,zn as a,FS as at,q as b,on as bt,ft as c,AS as ct,qw as d,ts as dt,cs as et,_ as f,NS as ft,Rw as g,it as gt,Wt as h,D as ht,nI as i,zS as it,mw as j,se as jt,JS as k,j as kt,oI as l,DS as lt,ce as m,Ae as mt,jn as n,PS as nt,Qw as o,MS as ot,Zt as p,xS as pt,qS as q,eo as r,RS as rt,Yw as s,OS as st,qn as t,VS as tt,Rn as u,as as ut,Po as v,LS as vt,B as w,et as wt,tI as x,tn as xt,de as y,ue as yt,gs as z,ui as zt};
|
|
78
|
+
- `+n.message+": "+n.details}return o}},$n=class extends EventTarget{static{h(this,"ComfyApi")}#e=new Set;api_host;api_base;initialClientId;clientId;user;socket=null;authStoreComposable;reportedUnknownMessageTypes=new Set;getClientFeatureFlags(){return{...ci}}serverFeatureFlags={};authToken;apiKey;constructor(){super(),this.user="",this.api_host=location.host,this.api_base=ke?"":location.pathname.split("/").slice(0,-1).join("/"),this.initialClientId=sessionStorage.getItem("clientId")}internalURL(o){return this.api_base+"/internal"+o}apiURL(o){return this.api_base+"/api"+o}fileURL(o){return this.api_base+o}async getAuthStore(){if(ke)return this.authStoreComposable||(this.authStoreComposable=(await R(()=>import("./firebaseAuthStore-DnNaPbuZ.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]),import.meta.url)).useFirebaseAuthStore),this.authStoreComposable()}async waitForAuthInitialization(){if(ke){const o=await this.getAuthStore();if(!o||o.isInitialized)return;try{await Promise.race([Jn(o.isInitialized),oi(1e4)])}catch{console.warn("Firebase auth initialization timeout after 10 seconds")}}}async fetchApi(o,e){const t=e?.headers??{};if(ke){await this.waitForAuthInitialization();const i=await h(async()=>{try{const s=await this.getAuthStore();return s?await s.getAuthHeader():null}catch(s){return console.warn("Failed to get auth header:",s),null}},"getAuthHeaderIfAvailable")();if(i)for(const[s,a]of Object.entries(i))Vo(t,s,a)}return Vo(t,"Comfy-User",this.user),fetch(this.apiURL(o),{cache:"no-cache",...e,headers:t})}addEventListener(o,e,t){super.addEventListener(o,e,t),this.#e.add(o)}removeEventListener(o,e,t){super.removeEventListener(o,e,t)}dispatchCustomEvent(o,e){const t=e===void 0?new CustomEvent(o):new CustomEvent(o,{detail:e});return super.dispatchEvent(t)}dispatchEvent(o){return super.dispatchEvent(o)}#t(){setInterval(async()=>{try{const o=await(await this.fetchApi("/prompt")).json();this.dispatchCustomEvent("status",o)}catch{this.dispatchCustomEvent("status",null)}},1e3)}async createSocket(o){if(this.socket)return;let e=!1,t=window.name;const n=new URLSearchParams;if(t&&n.set("clientId",t),ke)try{const r=await(await this.getAuthStore())?.getIdToken();r&&n.set("token",r)}catch(r){console.warn("Could not get auth token for WebSocket connection:",r)}const i=`${window.location.protocol==="https:"?"wss":"ws"}://${this.api_host}${this.api_base}/ws`,s=n.toString(),a=s?`${i}?${s}`:i;this.socket=new WebSocket(a),this.socket.binaryType="arraybuffer",this.socket.addEventListener("open",()=>{e=!0,this.socket.send(JSON.stringify({type:"feature_flags",data:this.getClientFeatureFlags()})),o&&this.dispatchCustomEvent("reconnected")}),this.socket.addEventListener("error",()=>{this.socket&&this.socket.close(),!o&&!e&&this.#t()}),this.socket.addEventListener("close",()=>{setTimeout(async()=>{this.socket=null,await this.createSocket(!0)},300),e&&(this.dispatchCustomEvent("status",null),this.dispatchCustomEvent("reconnecting"))}),this.socket.addEventListener("message",r=>{try{if(r.data instanceof ArrayBuffer){const l=new DataView(r.data),d=l.getUint32(0);let u;switch(d){case 3:const p=new TextDecoder,m=r.data.slice(4),g=l.getUint32(4);this.dispatchCustomEvent("progress_text",{nodeId:p.decode(m.slice(4,4+g)),text:p.decode(m.slice(4+g))});break;case 1:const f=l.getUint32(4),y=r.data.slice(8);switch(f){case 2:u="image/png";break;case 1:default:u="image/jpeg";break}const b=new Blob([y],{type:u});this.dispatchCustomEvent("b_preview",b);break;case 4:const v=new TextDecoder,k=l.getUint32(4),w=r.data.slice(8,8+k),S=JSON.parse(v.decode(w)),E=r.data.slice(8+k);let C=S.image_type;const I=new Blob([E],{type:C});this.dispatchCustomEvent("b_preview_with_metadata",{blob:I,nodeId:S.node_id,displayNodeId:S.display_node_id,parentNodeId:S.parent_node_id,realNodeId:S.real_node_id,promptId:S.prompt_id}),this.dispatchCustomEvent("b_preview",I);break;default:throw new Error(`Unknown binary websocket message of type ${d}`)}}else{const l=JSON.parse(r.data);switch(l.type){case"status":if(l.data.sid){const d=l.data.sid;this.clientId=d,window.name=d,sessionStorage.setItem("clientId",d)}this.dispatchCustomEvent("status",l.data.status??null);break;case"executing":this.dispatchCustomEvent("executing",l.data.display_node||l.data.node);break;case"execution_start":case"execution_error":case"execution_interrupted":case"execution_cached":case"execution_success":case"progress":case"progress_state":case"executed":case"graphChanged":case"promptQueued":case"logs":case"b_preview":case"notification":this.dispatchCustomEvent(l.type,l.data);break;case"feature_flags":this.serverFeatureFlags=l.data,this.serverFeatureFlags;break;default:if(this.#e.has(l.type))super.dispatchEvent(new CustomEvent(l.type,{detail:l.data}));else if(!this.reportedUnknownMessageTypes.has(l.type))throw this.reportedUnknownMessageTypes.add(l.type),new Error(`Unknown message type ${l.type}`)}}}catch(l){console.warn("Unhandled message:",r.data,l)}})}init(){this.createSocket()}async getExtensions(){return await(await this.fetchApi("/extensions",{cache:"no-store"})).json()}async getWorkflowTemplates(){return await(await this.fetchApi("/workflow_templates")).json()}async getCoreWorkflowTemplates(o){const e=o&&o!=="en"?`index.${o}.json`:"index.json";try{const t=await Ce.get(this.fileURL(`/templates/${e}`));return t.headers["content-type"]?.includes("application/json")?t.data:[]}catch(t){return o&&o!=="en"?(console.warn(`Localized templates for '${o}' not found, falling back to English`),this.getCoreWorkflowTemplates()):(console.error("Error loading core workflow templates:",t),[])}}async getEmbeddings(){return await(await this.fetchApi("/embeddings",{cache:"no-store"})).json()}async getNodeDefs(){return await(await this.fetchApi("/object_info",{cache:"no-store"})).json()}async queuePrompt(o,e,t){const{output:n,workflow:i}=e,s={client_id:this.clientId??"",prompt:n,...t?.partialExecutionTargets&&{partial_execution_targets:t.partialExecutionTargets},extra_data:{auth_token_comfy_org:this.authToken,api_key_comfy_org:this.apiKey,extra_pnginfo:{workflow:i},...t?.previewMethod&&t.previewMethod!=="default"&&{preview_method:t.previewMethod}}};o===-1?s.front=!0:o!=0&&(s.number=o);const a=await this.fetchApi("/prompt",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(a.status!==200)throw new qn(await a.json());return await a.json()}async getModelFolders(){const o=await this.fetchApi("/experiment/models");if(o.status===404)return[];const e=["configs","custom_nodes"];return(await o.json()).filter(t=>!e.includes(t.name))}async getModels(o){const e=await this.fetchApi(`/experiment/models/${o}`);return e.status===404?[]:await e.json()}async viewMetadata(o,e){const t=await this.fetchApi(`/view_metadata/${o}?filename=${encodeURIComponent(e)}`),n=await t.text();if(!n)return null;try{return JSON.parse(n)}catch(i){return console.error("Error viewing metadata",t.status,t.statusText,n,i),null}}async getItems(o){return o==="queue"?this.getQueue():this.getHistory()}async getQueue(){try{return await mS(this.fetchApi.bind(this))}catch(o){return console.error("Failed to fetch queue:",o),{Running:[],Pending:[]}}}async getHistory(o=200,e){try{return await pS(this.fetchApi.bind(this),o,e?.offset)}catch(t){return console.error(t),[]}}async getJobDetail(o){return hS(this.fetchApi.bind(this),o)}async getSystemStats(){return await(await this.fetchApi("/system_stats")).json()}async#o(o,e){try{await this.fetchApi("/"+o,{method:"POST",headers:{"Content-Type":"application/json"},body:e?JSON.stringify(e):void 0})}catch(t){console.error(t)}}async deleteItem(o,e){await this.#o(o,{delete:[e]})}async clearItems(o){await this.#o(o,{clear:!0})}async interrupt(o){await this.#o("interrupt",o?{prompt_id:o}:void 0)}async getUserConfig(){return(await this.fetchApi("/users")).json()}createUser(o){return this.fetchApi("/users",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:o})})}async getSettings(){const o=await this.fetchApi("/settings");if(o.status==401)throw new jn(o.statusText);return await o.json()}async getSetting(o){return(await this.fetchApi(`/settings/${encodeURIComponent(o)}`)).json()}async storeSettings(o){return this.fetchApi("/settings",{method:"POST",body:JSON.stringify(o)})}async storeSetting(o,e){return this.fetchApi(`/settings/${encodeURIComponent(o)}`,{method:"POST",body:JSON.stringify(e)})}async getUserData(o,e){return this.fetchApi(`/userdata/${encodeURIComponent(o)}`,e)}async storeUserData(o,e,t={overwrite:!0,stringify:!0,throwOnError:!0,full_info:!1}){const n=await this.fetchApi(`/userdata/${encodeURIComponent(o)}?overwrite=${t.overwrite}&full_info=${t.full_info}`,{method:"POST",body:t?.stringify?JSON.stringify(e):e,...t});if(n.status!==200&&t.throwOnError!==!1)throw new Error(`Error storing user data file '${o}': ${n.status} ${(await n).statusText}`);return n}async deleteUserData(o){return await this.fetchApi(`/userdata/${encodeURIComponent(o)}`,{method:"DELETE"})}async moveUserData(o,e,t={overwrite:!1}){return await this.fetchApi(`/userdata/${encodeURIComponent(o)}/move/${encodeURIComponent(e)}?overwrite=${t?.overwrite}`,{method:"POST"})}async listUserDataFullInfo(o){const e=Zn(o,"/"),t=await this.fetchApi(`/userdata?dir=${encodeURIComponent(e)}&recurse=true&split=false&full_info=true`);if(t.status===404)return[];if(t.status!==200)throw new Error(`Error getting user data list '${e}': ${t.status} ${t.statusText}`);return t.json()}async getGlobalSubgraphData(o){const e=await eo.fetchApi("/global_subgraphs/"+o);return e.status!==200?"":(await e.json())?.data??""}async getGlobalSubgraphs(){const o=await eo.fetchApi("/global_subgraphs");if(o.status!==200)return{};const e=await o.json();for(const[t,n]of Object.entries(e))n.data||(n.data=this.getGlobalSubgraphData(t));return e}async getLogs(){const o=ke?this.apiURL("/logs"):this.internalURL("/logs");return(await Ce.get(o)).data}async getRawLogs(){const o=ke?this.apiURL("/logs/raw"):this.internalURL("/logs/raw");return(await Ce.get(o)).data}async subscribeLogs(o){const e=ke?this.apiURL("/logs/subscribe"):this.internalURL("/logs/subscribe");return await Ce.patch(e,{enabled:o,clientId:this.clientId})}async getFolderPaths(){const o=await Ce.get(this.internalURL("/folder_paths")).catch(()=>null);return o?o.data:{}}async freeMemory(o){try{let e="";o.freeExecutionCache?e='{"unload_models": true, "free_memory": true}':e='{"unload_models": true}',(await this.fetchApi("/free",{method:"POST",headers:{"Content-Type":"application/json"},body:e})).status===200?o.freeExecutionCache?nt().add({severity:"success",summary:"Models and Execution Cache have been cleared.",life:3e3}):nt().add({severity:"success",summary:"Models have been unloaded.",life:3e3}):nt().add({severity:"error",summary:"Unloading of models failed. Installed ComfyUI may be an outdated version.",life:5e3})}catch{nt().add({severity:"error",summary:"An error occurred while trying to unload models.",life:5e3})}}async getCustomNodesI18n(){return(await Ce.get(this.apiURL("/i18n"))).data}serverSupportsFeature(o){return lo(this.serverFeatureFlags,o)===!0}getServerFeature(o,e){return lo(this.serverFeatureFlags,o,e)}getServerFeatures(){return{...this.serverFeatureFlags}}async getFuseOptions(){try{const o=await Ce.get(this.fileURL("/templates/fuse_options.json"),{headers:{"Content-Type":"application/json"}});return o.headers["content-type"]?.includes("application/json")?o.data:null}catch(o){return console.error("Error loading fuse options:",o),null}}};const eo=new $n;window.comfyAPI=window.comfyAPI||{};window.comfyAPI.api=window.comfyAPI.api||{};window.comfyAPI.api.UnauthorizedError=jn;window.comfyAPI.api.PromptExecutionError=qn;window.comfyAPI.api.ComfyApi=$n;window.comfyAPI.api.api=eo;export{$S as $,ye as A,M as At,XS as B,Uo as Bt,Cw as C,en as Ct,YS as D,O as Dt,It as E,H as Et,ks as F,CS as Ft,Ge as G,US as H,wS as Ht,z as I,nt as It,KS as J,jS as K,So as L,ke as Lt,J as M,zi as Mt,_n as N,TS as Nt,QS as O,re as Ot,vs as P,Mi as Pt,un as Q,io as R,IS as Rt,eI as S,Gi as St,ZS as T,xe as Tt,ps as U,ms as V,SS as Vt,WS as W,GS as X,BS as Y,HS as Z,gt as _,ES as _t,zn as a,FS as at,q as b,on as bt,ft as c,AS as ct,qw as d,ts as dt,cs as et,_ as f,NS as ft,Rw as g,it as gt,Wt as h,D as ht,nI as i,zS as it,mw as j,se as jt,JS as k,j as kt,oI as l,DS as lt,ce as m,Ae as mt,jn as n,PS as nt,Qw as o,MS as ot,Zt as p,xS as pt,qS as q,eo as r,RS as rt,Yw as s,OS as st,qn as t,VS as tt,Rn as u,as as ut,Po as v,LS as vt,B as w,et as wt,tI as x,tn as xt,de as y,ue as yt,gs as z,ui as zt};
|
|
79
79
|
|
|
80
|
-
//# sourceMappingURL=api-
|
|
80
|
+
//# sourceMappingURL=api-Dwq2LQIW.js.map
|