diff --git a/calliope-backend/scripts/audit_reference_conversion.py b/calliope-backend/scripts/audit_reference_conversion.py
index c0e5169e..a87365db 100644
--- a/calliope-backend/scripts/audit_reference_conversion.py
+++ b/calliope-backend/scripts/audit_reference_conversion.py
@@ -39,7 +39,12 @@ from calliope.comfyui.serialization_reference import (
serialize_promoted_node,
serialize_reference_widgets,
)
-from calliope.comfyui.structure_reference import PROMOTED_PROFILES, STRUCTURE_PROFILES
+from calliope.comfyui.structure_reference import (
+ PROMOTED_PROFILES,
+ SETGET_COMMIT,
+ SETGET_PROFILES,
+ STRUCTURE_PROFILES,
+)
from calliope.comfyui.ui2api import convert, convert_reference
@@ -293,6 +298,7 @@ REFERENCE_PROFILES = (
SEPARATION_PROFILE,
*CROP_SPLIT_PROFILES,
*VHS_PROFILES,
+ *SETGET_PROFILES,
)
@@ -495,6 +501,7 @@ def profile_attempt(source, profile):
**PROMOTED_PROFILES,
CASE04_PROFILE: "1.53.6",
**VHS_PROFILES,
+ **SETGET_PROFILES,
}.get(profile, "1.37.11")
assumptions = {
"frontend": expected,
@@ -572,6 +579,38 @@ def profile_attempt(source, profile):
"serialization-evidence/sources.json",
]
base = {"profile": profile, "assumptions": assumptions}
+ if profile in SETGET_PROFILES:
+ assumptions["setget_reference"] = {
+ "commit": SETGET_COMMIT,
+ "missing_version": "explicit_fixed_reference_assumption_only",
+ "provider_policy": "exact_aux_id_required; missing/literal/conflict_rejected",
+ "scope": "root_only; nested_and_cross_boundary_rejected",
+ "name": "widgets_values/0 exact string; no normalization or previousName lookup",
+ "duplicates": "reject_all; frontend_first_match_is_not_emulated",
+ "unmodified_pinned_extensions": True,
+ "target_installation_and_UE_match": "unknown",
+ }
+ assumptions["reference_sources"] = [
+ "setget-reference/sources.json",
+ "vhs-reference/sources.json",
+ "serialization-evidence/sources.json",
+ ]
+ base["verified_reference_facts"] = "setget-reference/contract.json"
+ base["source_declarations"] = [
+ {
+ "pointer": f"/nodes/{i}",
+ **{k: (n.get("properties") or {}).get(k) for k in ("cnr_id", "aux_id", "ver")},
+ }
+ for i, n in enumerate(source.get("nodes", []))
+ ]
+ if not any(n.get("type") in ("SetNode", "GetNode") for n in source.get("nodes", [])):
+ return {
+ **base,
+ "status": "not_applicable",
+ "issues": [
+ {"code": "setget_not_present", "message": "新profile仅覆盖包含Set/Get的根图"}
+ ],
+ }
if profile in (*CROP_SPLIT_PROFILES, *VHS_PROFILES):
base["source_declarations"] = [
{
@@ -594,21 +633,29 @@ def profile_attempt(source, profile):
else "requires_explicit_1.48.6"
)
assumptions["missing_frontend_policy"] = (
- "explicit_media_reference_assumption"
+ "explicit_1.37.11_reference_assumption"
+ if profile in SETGET_PROFILES
+ else "explicit_media_reference_assumption"
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES, *VHS_PROFILES)
else "explicit_legacy_reference_assumption"
if profile in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE)
else "requires_explicit_declaration"
)
- if profile in VHS_PROFILES and expected == "1.48.6":
+ if profile in (*VHS_PROFILES, *SETGET_PROFILES) and expected == "1.48.6":
assumptions["missing_frontend_policy"] = "requires_explicit_1.48.6"
assumptions["missing_node_declarations"] = [
n["pointer"]
- for n in node_inventory(source, include_aux=profile in CROP_SPLIT_PROFILES)
+ for n in node_inventory(
+ source, include_aux=profile in (*CROP_SPLIT_PROFILES, *SETGET_PROFILES)
+ )
if n["type"] not in ("Note", "MarkdownNote", "Reroute", "PrimitiveNode")
and (n["provider"] is None or n["version"] is None)
]
- if (profile in VHS_PROFILES and expected == "1.48.6" and declared_frontend is None) or (
+ if (
+ profile in (*VHS_PROFILES, *SETGET_PROFILES)
+ and expected == "1.48.6"
+ and declared_frontend is None
+ ) or (
declared_frontend != expected
and not (
declared_frontend is None
@@ -621,6 +668,7 @@ def profile_attempt(source, profile):
SEPARATION_PROFILE,
*CROP_SPLIT_PROFILES,
*VHS_PROFILES,
+ *SETGET_PROFILES,
)
)
):
@@ -644,6 +692,11 @@ def profile_attempt(source, profile):
else "serializer_or_structure_rejected",
"issues": result.issues,
"unresolved_boundaries": result.unresolved_boundaries,
+ **(
+ {"virtual_resolutions": result.virtual_resolutions}
+ if profile in SETGET_PROFILES
+ else {}
+ ),
}
# Legacy core serializers explicitly assume absent declarations. Record
# that assumption instead of implying that a type-name match proved it.
@@ -655,6 +708,11 @@ def profile_attempt(source, profile):
or "restored_saved_state_before_queue_hooks",
"candidate_sha256": canonical_sha(result.prompt),
"candidate_prompt": result.prompt,
+ **(
+ {"virtual_resolutions": result.virtual_resolutions}
+ if profile in SETGET_PROFILES
+ else {}
+ ),
**(
{"field_evidence": asr_field_evidence(source, result.prompt)}
if profile == ASR_PROFILE
@@ -740,7 +798,7 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles=
for issue in attempt["issues"]:
gap_inventory = (
node_inventory(source, include_aux=True)
- if attempt["profile"] in CROP_SPLIT_PROFILES
+ if attempt["profile"] in (*CROP_SPLIT_PROFILES, *SETGET_PROFILES)
else inventory
)
matches = [n for n in gap_inventory if n["node_id"] == issue.get("node_id")]
@@ -766,7 +824,11 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles=
}
if baseline_profiles is None:
excluded_profiles = (
- VHS_PROFILES if any(p in VHS_PROFILES for p in profiles) else CROP_SPLIT_PROFILES
+ SETGET_PROFILES
+ if any(p in SETGET_PROFILES for p in profiles)
+ else VHS_PROFILES
+ if any(p in VHS_PROFILES for p in profiles)
+ else CROP_SPLIT_PROFILES
)
baseline_profiles = tuple(p for p in profiles if p not in excluded_profiles)
old_complete = {
diff --git a/calliope-backend/src/calliope/comfyui/serialization_reference.py b/calliope-backend/src/calliope/comfyui/serialization_reference.py
index b79a15d4..4bb01e2f 100644
--- a/calliope-backend/src/calliope/comfyui/serialization_reference.py
+++ b/calliope-backend/src/calliope/comfyui/serialization_reference.py
@@ -14,6 +14,8 @@ import json
import math
from typing import Any
+from .structure_reference import SETGET_PROFILES
+
MP3_PROFILE = "comfy-frontend-1.37.11-mp3-core-0.11.0-reference"
REEL_PROFILE = "comfy-frontend-1.37.11-layerstyle-mixed-core-0.4.0-reference"
MEDIA_PROFILES = (MP3_PROFILE, REEL_PROFILE)
@@ -100,6 +102,8 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]:
"output": outputs,
}
+ if profile in SETGET_PROFILES:
+ return {**reference_definitions(PROFILE), **vhs_definitions()}
if profile in VHS_PROFILES:
return vhs_definitions()
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES):
@@ -176,6 +180,16 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]:
def serialize_reference_widgets(node: dict[str, Any], profile: str = PROFILE) -> dict[str, Any]:
"""Apply only the pinned identity serializers; reject any extra/missing value."""
+ if profile in SETGET_PROFILES:
+ if node.get("type") in vhs_definitions():
+ return serialize_vhs_node(node)
+ if any(
+ k in container
+ for container in (node, node.get("properties") or {})
+ for k in ("widgets", "widgets_values_named", "serializeValue", "comfyDynamic")
+ ):
+ raise ValueError("Set/Get组合核心参考不接受自定义serializer或额外控件")
+ return serialize_reference_widgets(node, PROFILE)
if profile in VHS_PROFILES:
return serialize_vhs_node(node)
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES):
diff --git a/calliope-backend/src/calliope/comfyui/structure_reference.py b/calliope-backend/src/calliope/comfyui/structure_reference.py
index 596205ed..e571b7b7 100644
--- a/calliope-backend/src/calliope/comfyui/structure_reference.py
+++ b/calliope-backend/src/calliope/comfyui/structure_reference.py
@@ -7,11 +7,17 @@ node serializers, third-party behavior, target versions or execution eligibility
from __future__ import annotations
+import re
from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any
from uuid import UUID
+SETGET_COMMIT = "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18"
+SETGET_PROFILES = {
+ f"comfy-frontend-{v}-kj-setget-ab72eda7-vhs-reference": v for v in ("1.37.11", "1.48.6")
+}
+
STRUCTURE_PROFILES = {
f"comfy-frontend-{version}-structure-reference": version
for version in ("1.48.7", "1.53.6", "1.48.6")
@@ -44,6 +50,292 @@ def _uuid(value):
return False
+def project_reference_setget(source: dict) -> Structure:
+ """Pinned KJ same-root saved-state projection, never a partial prompt.
+
+ Diagnostics may retain literal, unique-name topology when provenance is
+ ambiguous. Such paths carry rejections and NEVER yield a projected graph.
+ Every virtual node, edge and dependency cycle is checked, including unused
+ branches. No subgraph scope, rename callback or type inference is emulated.
+ """
+ from .serialization_reference import validate_reroute
+
+ issues, resolved = [], []
+
+ def reject(message, nid=""):
+ issues.append({"code": "setget_reference_invalid", "node_id": str(nid), "message": message})
+
+ try:
+ if (source.get("definitions") or {}).get("subgraphs") or any(
+ _uuid(n.get("type")) for n in source["nodes"]
+ ):
+ reject("Set/Get仅覆盖根图;嵌套或跨边界名字作用域未证明")
+ if any((source.get("extra") or {}).get(k) for k in ("ue_links", "links_added_by_ue")):
+ raise ValueError("Set/Get不解释UE附加连线")
+ nodes, indices, links, link_indices = {}, {}, {}, {}
+ for i, n in enumerate(source["nodes"]):
+ nid = _id(n["id"])
+ if nid in nodes:
+ raise ValueError("重复根图节点ID")
+ nodes[nid], indices[nid] = n, i
+ if n.get("type") not in ("Note", "MarkdownNote") and (
+ type(n.get("mode", 0)) is not int or n.get("mode", 0) != 0
+ ):
+ reject("根图运行节点仅支持正常mode=0", nid)
+ if any(
+ k in container
+ for container in (n, n.get("properties") or {})
+ for k in (
+ "getInputLink",
+ "resolveInput",
+ "resolveOutput",
+ "onExecute",
+ "isVirtualNode",
+ "applyToGraph",
+ )
+ ):
+ reject("根图含自定义执行/追线覆盖", nid)
+ for i, edge in enumerate(source.get("links", [])):
+ if not isinstance(edge, list) or len(edge) != 6:
+ raise ValueError("Set/Get仅接受六字段根图连线")
+ lid, a, oslot, b, islot, typ = edge
+ if type(lid) is not int or lid < 0 or lid in links:
+ raise ValueError("连线ID非法或重复")
+ a, b = _id(a), _id(b)
+ for nid, slot, direction in ((a, oslot, "outputs"), (b, islot, "inputs")):
+ if (
+ nid not in nodes
+ or type(slot) is not int
+ or not (0 <= slot < len(nodes[nid].get(direction, [])))
+ ):
+ raise ValueError("连线端点/原槽缺失")
+ s = nodes[nid][direction][slot]
+ if direction == "outputs":
+ ids = s.get("links") or []
+ if any(type(x) is not int for x in ids) or ids.count(lid) != 1:
+ raise ValueError("输出与连线不互指")
+ elif type(s.get("link")) is not int or s["link"] != lid:
+ raise ValueError("输入与连线不互指")
+ if s.get("type") != typ:
+ raise ValueError("每跳连线类型与两端槽必须精确一致")
+ if not isinstance(typ, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", typ):
+ raise ValueError("通配/联合/动态连线类型未证明")
+ links[lid], link_indices[lid] = edge, i
+ for nid, n in nodes.items():
+ for direction in ("inputs", "outputs"):
+ for slot, s in enumerate(n.get(direction, [])):
+ ids = (
+ [s["link"]]
+ if direction == "inputs" and s.get("link") is not None
+ else (s.get("links") or [])
+ if direction == "outputs"
+ else []
+ )
+ for lid in ids:
+ e = links.get(lid)
+ offset = 1 if direction == "outputs" else 3
+ if e is None or [str(e[offset]), e[offset + 1]] != [nid, slot]:
+ raise ValueError("槽引用缺失连线或错误端点")
+
+ setters, names, node_rejections = {}, {}, {}
+ virtual = {
+ nid for nid, n in nodes.items() if n.get("type") in ("SetNode", "GetNode", "Reroute")
+ }
+ for nid in sorted(virtual):
+ n = nodes[nid]
+ start = len(issues)
+ if type(n.get("mode", 0)) is not int or n.get("mode", 0) != 0:
+ reject("Set/Get/Reroute只支持正常mode=0", nid)
+ if n["type"] == "Reroute":
+ try:
+ validate_reroute(n)
+ except ValueError as exc:
+ reject(str(exc), nid)
+ types = [s.get("type") for s in n.get("inputs", []) + n.get("outputs", [])]
+ if (
+ len(types) != 2
+ or types[0] != types[1]
+ or not isinstance(types[0], str)
+ or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", types[0])
+ ):
+ reject("Reroute仅支持已保存且精确相同的具体类型", nid)
+ else:
+ props = n.get("properties") or {}
+ if (
+ props.get("aux_id") != "kijai/ComfyUI-KJNodes"
+ or props.get("cnr_id") is not None
+ ):
+ reject("Set/Get提供方歧义或冲突;类名字面aux_id不是来源证明", nid)
+ if props.get("ver") not in (None, SETGET_COMMIT):
+ reject("Set/Get显式版本不等于固定完整提交", nid)
+ values = n.get("widgets_values")
+ if (
+ not isinstance(values, list)
+ or len(values) != 1
+ or type(values[0]) is not str
+ or not values[0]
+ ):
+ reject("Set/Get要求唯一非空字符串名字控件", nid)
+ else:
+ names[nid] = values[0]
+ if n["type"] == "SetNode":
+ setters.setdefault(values[0], []).append(nid)
+ if (
+ len(n.get("inputs", [])) != (1 if n["type"] == "SetNode" else 0)
+ or len(n.get("outputs", [])) != 1
+ ):
+ reject("Set/Get有额外或缺失槽", nid)
+ sockets = n.get("inputs", []) + n.get("outputs", [])
+ types = [s.get("type") for s in sockets]
+ if (
+ not types
+ or any(
+ not isinstance(t, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", t)
+ for t in types
+ )
+ or len(set(types)) != 1
+ ):
+ reject("Set/Get槽类型未知或不一致;不按名字推断类型", nid)
+ if any(s.get("name") != s.get("type") or s.get("widget") for s in sockets):
+ reject("Set/Get槽构造/绑定与固定形式不符", nid)
+ for container in (n, n.get("properties") or {}):
+ if any(
+ k in container
+ for k in (
+ "widgets",
+ "widgets_values_named",
+ "serializeValue",
+ "comfyDynamic",
+ "getInputLink",
+ "onExecute",
+ "isVirtualNode",
+ )
+ ):
+ reject("虚拟节点存在自定义覆盖或额外控件", nid)
+ props = n.get("properties") or {}
+ ue = props.get("ue_properties") or {}
+ if any(
+ props.get(k) or ue.get(k)
+ for k in ("widget_ue_connectable", "input_ue_unconnectable")
+ ):
+ reject("虚拟节点UE自定义绑定未证明", nid)
+ node_rejections[nid] = issues[start:]
+ for name, ids in setters.items():
+ if len(ids) != 1:
+ reject(f"重名Set:{name!r};保守拒绝而非取首个")
+
+ def trace(nid, slot, seen=()):
+ token = (nid, slot)
+ if token in seen:
+ raise ValueError("Set/Get逻辑环或链式自引用")
+ n = nodes[nid]
+ hop = {
+ "node_id": nid,
+ "output_slot": slot,
+ "node_pointer": f"/nodes/{indices[nid]}",
+ "output_pointer": f"/nodes/{indices[nid]}/outputs/{slot}",
+ }
+ if nid not in virtual:
+ return [nid, slot], [hop], []
+ if slot != 0:
+ raise ValueError("虚拟节点出口必须为零槽")
+ rejection = list(node_rejections[nid])
+ if nid in names:
+ hop.update(name=names[nid], name_pointer=hop["node_pointer"] + "/widgets_values/0")
+ if n["type"] == "GetNode":
+ ids = setters.get(names.get(nid), [])
+ if len(ids) != 1:
+ raise ValueError("Get缺少唯一精确名字Set;不使用previousName/标题或规范化")
+ sid = ids[0]
+ if n["outputs"][0]["type"] != nodes[sid]["outputs"][0]["type"]:
+ raise ValueError("Get与Set类型冲突")
+ endpoint, hops, errors = trace(sid, 0, (*seen, token))
+ hop.update(
+ name=names[nid],
+ name_pointer=hop["node_pointer"] + "/widgets_values/0",
+ setter_id=sid,
+ )
+ return endpoint, [hop, *hops], rejection + errors
+ lid = n.get("inputs", [{}])[0].get("link")
+ if lid not in links:
+ raise ValueError("Set/Reroute无上游实际输入")
+ e = links[lid]
+ hop.update(input_slot=0, link_pointer=f"/links/{link_indices[lid]}", original_link=e)
+ endpoint, hops, errors = trace(str(e[1]), e[2], (*seen, token))
+ return endpoint, [hop, *hops], rejection + errors
+
+ # Include logical binding edges when checking ALL cycles, including
+ # ordinary-node cycles containing a Set/Get hop and unused bad branches.
+ adjacency = {nid: [] for nid in nodes}
+ for e in links.values():
+ adjacency[str(e[1])].append(str(e[3]))
+ for nid, n in nodes.items():
+ if n.get("type") == "GetNode" and len(setters.get(names.get(nid), [])) == 1:
+ adjacency[setters[names[nid]][0]].append(nid)
+ indegree = dict.fromkeys(nodes, 0)
+ for targets in adjacency.values():
+ for t in targets:
+ indegree[t] += 1
+ pending = [k for k, v in indegree.items() if not v]
+ visited = 0
+ while pending:
+ visited += 1
+ for target in adjacency[pending.pop()]:
+ indegree[target] -= 1
+ if not indegree[target]:
+ pending.append(target)
+ if visited != len(nodes):
+ reject("根图含物理或Set/Get逻辑依赖环")
+ # Resolve every virtual node, even if its output has no consumers.
+ for nid in sorted(virtual):
+ try:
+ trace(nid, 0)
+ except (ValueError, KeyError, IndexError, TypeError) as exc:
+ reject(str(exc), nid)
+ graph = deepcopy(source)
+ kept = {str(n["id"]): n for n in graph["nodes"] if str(n["id"]) not in virtual}
+ edges = []
+ for e in links.values():
+ if str(e[3]) in virtual:
+ continue
+ try:
+ endpoint, hops, errors = trace(str(e[1]), e[2])
+ if str(e[1]) in virtual:
+ resolved.append(
+ {
+ "target_node_id": str(e[3]),
+ "target_input_slot": e[4],
+ "target_input_name": nodes[str(e[3])]["inputs"][e[4]]["name"],
+ "original_link_pointer": f"/links/{link_indices[e[0]]}",
+ "original_link": e,
+ "endpoint": endpoint,
+ "hops": hops,
+ "binding_rejections": errors,
+ "authority": "literal_topology_only"
+ if errors or issues
+ else "pinned_reference_assumption_only",
+ }
+ )
+ edges.append([e[0], int(endpoint[0]), endpoint[1], *e[3:]])
+ except (ValueError, KeyError, IndexError, TypeError) as exc:
+ reject(str(exc), e[3])
+ if issues:
+ for resolution in resolved:
+ resolution["whole_graph_rejected"] = True
+ resolution["authority"] = "literal_topology_only"
+ return Structure(None, issues, resolved=resolved)
+ for n in kept.values():
+ for s in n.get("outputs", []):
+ s["links"] = []
+ for e in edges:
+ kept[str(e[1])]["outputs"][e[2]]["links"].append(e[0])
+ graph["nodes"], graph["links"] = list(kept.values()), edges
+ return Structure(graph, resolved=resolved)
+ except (ValueError, TypeError, KeyError, IndexError, AttributeError, RecursionError) as exc:
+ reject(str(exc))
+ return Structure(None, issues, resolved=resolved)
+
+
def expand_reference_subgraphs(
source: dict, profile: str, *, widgets: bool = False, case04: bool = False
) -> Structure:
diff --git a/calliope-backend/src/calliope/comfyui/ui2api.py b/calliope-backend/src/calliope/comfyui/ui2api.py
index 5dd00ffe..bd20657d 100644
--- a/calliope-backend/src/calliope/comfyui/ui2api.py
+++ b/calliope-backend/src/calliope/comfyui/ui2api.py
@@ -34,7 +34,13 @@ from .serialization_reference import (
serialize_reference_widgets,
validate_reroute,
)
-from .structure_reference import PROMOTED_PROFILES, STRUCTURE_PROFILES, expand_reference_subgraphs
+from .structure_reference import (
+ PROMOTED_PROFILES,
+ SETGET_PROFILES,
+ STRUCTURE_PROFILES,
+ expand_reference_subgraphs,
+ project_reference_setget,
+)
@dataclass
@@ -46,6 +52,7 @@ class Conversion:
unresolved_boundaries: list[dict[str, Any]] = field(default_factory=list)
resolved_boundaries: list[dict[str, Any]] = field(default_factory=list)
serialization_stage: str | None = None
+ virtual_resolutions: list[dict[str, Any]] = field(default_factory=list)
def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversion:
@@ -67,6 +74,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
SEPARATION_PROFILE,
*CROP_SPLIT_PROFILES,
*VHS_PROFILES,
+ *SETGET_PROFILES,
AUX_PROFILE,
PRIMITIVE_PROFILE,
PREVIEW_PROFILE,
@@ -83,6 +91,27 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
True,
)
try:
+ if profile in SETGET_PROFILES:
+ expected = SETGET_PROFILES[profile]
+ declared = (source.get("extra") or {}).get("frontendVersion")
+ if declared != expected and not (declared is None and expected == "1.37.11"):
+ raise ValueError("Set/Get前端声明不匹配;缺失仅显式选择1.37.11")
+ structure = project_reference_setget(source)
+ if structure.graph is None:
+ return Conversion(
+ None, structure.issues, True, virtual_resolutions=structure.resolved
+ )
+ result = _convert(
+ structure.graph,
+ reference_definitions(profile),
+ reference=True,
+ reference_profile=profile,
+ )
+ result.reference_only = True
+ result.virtual_resolutions = structure.resolved
+ result.diagnostic_graph = structure.graph
+ result.serialization_stage = "restored_saved_state_before_queue_hooks"
+ return result
if (
profile in VHS_PROFILES
and VHS_PROFILES[profile] == "1.48.6"
@@ -226,6 +255,7 @@ def _convert(
**PROMOTED_PROFILES,
CASE04_PROFILE: "1.53.6",
**VHS_PROFILES,
+ **SETGET_PROFILES,
}.get(reference_profile, "1.37.11")
if frontend_version is not None and frontend_version != expected_version:
fail("reference_frontend_mismatch", "源图声明的前端版本与固定参考不一致")
diff --git a/calliope-backend/tests/test_audio_separation_reference.py b/calliope-backend/tests/test_audio_separation_reference.py
index c8d5a9e1..22a0809c 100644
--- a/calliope-backend/tests/test_audio_separation_reference.py
+++ b/calliope-backend/tests/test_audio_separation_reference.py
@@ -362,7 +362,7 @@ def test_library_actual_delta_keeps_every_old_attempt_and_all_six_golden_compari
profiles = tuple(
p
for p in audit.REFERENCE_PROFILES
- if p not in (*audit.CROP_SPLIT_PROFILES, *audit.VHS_PROFILES)
+ if p not in (*audit.CROP_SPLIT_PROFILES, *audit.VHS_PROFILES, *audit.SETGET_PROFILES)
)
baseline = tuple(p for p in profiles if p != SEPARATION_PROFILE)
old = audit.audit_library(REPO, baseline)
diff --git a/calliope-backend/tests/test_crop_split_reference.py b/calliope-backend/tests/test_crop_split_reference.py
index dd9f46a9..f41a9e74 100644
--- a/calliope-backend/tests/test_crop_split_reference.py
+++ b/calliope-backend/tests/test_crop_split_reference.py
@@ -351,7 +351,9 @@ def test_two_disjoint_instances_preserve_nodes_links_and_values(profile):
def test_all_old_fourteen_profiles_attempts_gaps_and_six_differences_unchanged():
- historical_profiles = tuple(p for p in audit.REFERENCE_PROFILES if p not in VHS_PROFILES)
+ historical_profiles = tuple(
+ p for p in audit.REFERENCE_PROFILES if p not in (*VHS_PROFILES, *audit.SETGET_PROFILES)
+ )
profiles = tuple(p for p in historical_profiles if p not in CROP_SPLIT_PROFILES)
historical = json.loads((REPO / "docs/hel-892/separation-evidence/library.json").read_bytes())
baseline = audit.audit_library(REPO, profiles)
diff --git a/calliope-backend/tests/test_setget_reference.py b/calliope-backend/tests/test_setget_reference.py
new file mode 100644
index 00000000..84430151
--- /dev/null
+++ b/calliope-backend/tests/test_setget_reference.py
@@ -0,0 +1,423 @@
+"""Saved-state transformation tests; never execute upstream JS or a ComfyUI job."""
+
+from __future__ import annotations
+
+import copy
+import json
+from pathlib import Path
+
+import pytest
+from scripts import audit_reference_conversion as audit
+from scripts.verify_frontend_sources import verify
+
+from calliope.comfyui.structure_reference import (
+ SETGET_PROFILES,
+ project_reference_setget,
+)
+from calliope.comfyui.ui2api import convert, convert_reference
+
+REPO = Path(__file__).resolve().parents[2]
+PROFILE = next(iter(SETGET_PROFILES))
+
+
+def virtual(nid, kind, name, typ="IMAGE"):
+ return {
+ "id": nid,
+ "type": kind,
+ "mode": 0,
+ "properties": {"aux_id": "kijai/ComfyUI-KJNodes", "previousName": "old"},
+ "widgets_values": [name],
+ "inputs": [{"name": typ, "type": typ, "link": None}] if kind == "SetNode" else [],
+ "outputs": [{"name": typ, "type": typ, "links": []}],
+ }
+
+
+def connect(graph, lid, origin, oslot, target, tslot, typ="IMAGE"):
+ nodes = {n["id"]: n for n in graph["nodes"]}
+ nodes[origin]["outputs"][oslot].setdefault("links", []).append(lid)
+ nodes[target]["inputs"][tslot]["link"] = lid
+ graph["links"].append([lid, origin, oslot, target, tslot, typ])
+
+
+def synthetic():
+ graph = {
+ "nodes": [
+ {
+ "id": 1,
+ "type": "LoadImage",
+ "widgets_values": ["one.png", "image"],
+ "inputs": [],
+ "outputs": [{"type": "IMAGE", "links": []}, {"type": "MASK", "links": []}],
+ },
+ virtual(2, "SetNode", "图片"),
+ virtual(3, "GetNode", "图片"),
+ {
+ "id": 4,
+ "type": "PreviewImage",
+ "widgets_values": [],
+ "inputs": [{"name": "images", "type": "IMAGE", "link": None}],
+ "outputs": [],
+ },
+ ],
+ "links": [],
+ }
+ connect(graph, 1, 1, 0, 2, 0)
+ connect(graph, 2, 3, 0, 4, 0)
+ return graph
+
+
+def test_fixed_originals_and_registration_call_chain():
+ root = REPO / "docs/hel-892/setget-reference"
+ assert len(verify(root)["sources_verified"]) == 19
+ js = (root / "web__js__setgetnodes.js").read_text()
+ for text in (
+ 'LiteGraph.registerNodeType("SetNode", SetNode)',
+ 'LiteGraph.registerNodeType("GetNode", GetNode)',
+ "this.isVirtualNode = true",
+ "getInputLink(slot)",
+ "n.type === 'SetNode' && n.widgets[0].value === name",
+ "if (app.configuringGraph) return;",
+ "if (this._justAdded && !app.configuringGraph)",
+ "this.properties.previousName = this.widgets[0].value;",
+ ):
+ assert text in js
+ for v in SETGET_PROFILES.values():
+ dto = (root / f"{v}__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts").read_text()
+ assert "const virtualLink = this.node.getInputLink(slot)" in dto
+ assert "return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type)" in dto
+ node = (root / f"{v}__src__lib__litegraph__src__LGraphNode.ts").read_text()
+ assert "widget.value = info.widgets_values[i++]" in node
+ assert "getInputLink(slot: number)" in node
+
+
+@pytest.mark.parametrize("profile", SETGET_PROFILES)
+def test_complete_projection_and_production_stays_closed(profile):
+ g = synthetic()
+ g["extra"] = {"frontendVersion": SETGET_PROFILES[profile]}
+ original = copy.deepcopy(g)
+ result = convert_reference(g, profile)
+ assert result.prompt is not None, result.issues
+ assert set(result.prompt) == {"1", "4"}
+ assert result.prompt["4"]["inputs"]["images"] == ["1", 0]
+ assert result.prompt["1"]["inputs"]["image"] == "one.png"
+ assert [h["node_id"] for h in result.virtual_resolutions[0]["hops"]] == ["3", "2", "1"]
+ assert result.reference_only
+ assert convert(g).prompt is None
+ assert g == original
+
+
+@pytest.mark.parametrize("name", ["图片", " A ", "a", "A", "e\u0301", "\u00e9", " "])
+def test_exact_names_rename_previous_name_and_upstream_changes(name):
+ g = synthetic()
+ g["nodes"][1]["widgets_values"] = [name]
+ g["nodes"][2]["widgets_values"] = [name]
+ g["nodes"][1]["properties"]["previousName"] = "图片"
+ result = convert_reference(g, PROFILE)
+ assert result.prompt is not None
+ assert result.virtual_resolutions[0]["hops"][0]["name"] == name
+ g["nodes"][0]["widgets_values"][0] = "changed.png"
+ assert convert_reference(g, PROFILE).prompt["1"]["inputs"]["image"] == "changed.png"
+ g["nodes"][2]["widgets_values"] = ["not_current"]
+ g["nodes"][1]["properties"]["previousName"] = "not_current"
+ g["nodes"][1]["title"] = "not_current"
+ assert convert_reference(g, PROFILE).prompt is None
+
+
+@pytest.mark.parametrize("other", ["a", "A ", " A", "e\u0301"])
+def test_no_name_normalization(other):
+ g = synthetic()
+ g["nodes"][1]["widgets_values"] = ["A" if other != "e\u0301" else "\u00e9"]
+ g["nodes"][2]["widgets_values"] = [other]
+ assert convert_reference(g, PROFILE).prompt is None
+
+
+def test_multiple_names_and_changing_binding_selects_correct_source():
+ g = synthetic()
+ other = copy.deepcopy(g["nodes"][0])
+ other["id"] = 11
+ other["widgets_values"][0] = "two.png"
+ other["outputs"][0]["links"] = []
+ g["nodes"] += [other, virtual(12, "SetNode", "second")]
+ connect(g, 11, 11, 0, 12, 0)
+ assert convert_reference(g, PROFILE).prompt["4"]["inputs"]["images"] == ["1", 0]
+ g["nodes"][2]["widgets_values"] = ["second"]
+ result = convert_reference(g, PROFILE)
+ assert result.prompt["4"]["inputs"]["images"] == ["11", 0]
+ assert result.prompt["11"]["inputs"]["image"] == "two.png"
+
+
+def test_fanout_direct_set_and_multilevel_reroute_preserve_original_slot():
+ g = synthetic()
+ g["nodes"][0]["outputs"][1]["type"] = "IMAGE" # topology fixture only
+ g["nodes"][0]["outputs"][0]["links"] = []
+ g["nodes"][0]["outputs"][1]["links"] = [1]
+ g["links"][0][2] = 1
+ g["nodes"] += [
+ virtual(5, "GetNode", "图片"),
+ virtual(6, "SetNode", "next"),
+ virtual(7, "GetNode", "next"),
+ {
+ "id": 8,
+ "type": "Reroute",
+ "widgets_values": [],
+ "inputs": [{"name": "", "type": "IMAGE", "link": None}],
+ "outputs": [{"name": "", "type": "IMAGE", "links": []}],
+ },
+ copy.deepcopy(g["nodes"][3]),
+ ]
+ g["nodes"][-1]["id"] = 9
+ g["nodes"][-1]["inputs"][0]["link"] = None
+ connect(g, 3, 5, 0, 6, 0)
+ connect(g, 4, 7, 0, 8, 0)
+ connect(g, 5, 8, 0, 9, 0)
+ # Direct Set output feeds an additional sink; Get fanout is independent.
+ sink = copy.deepcopy(g["nodes"][3])
+ sink["id"] = 10
+ sink["inputs"][0]["link"] = None
+ g["nodes"].append(sink)
+ connect(g, 6, 2, 0, 10, 0)
+ projected = project_reference_setget(g)
+ assert projected.graph is not None, projected.issues
+ assert {tuple(e["endpoint"]) for e in projected.resolved} == {("1", 1)}
+ assert len(projected.resolved) == 3
+ last = next(r for r in projected.resolved if r["target_node_id"] == "9")
+ assert [h["node_id"] for h in last["hops"]] == ["8", "7", "6", "5", "2", "1"]
+ assert [e[2] for e in projected.graph["links"]] == [1, 1, 1]
+
+
+@pytest.mark.parametrize(
+ "mutation",
+ [
+ "duplicate",
+ "missing_set",
+ "empty",
+ "bad_name",
+ "extra_widget",
+ "mapping_widget",
+ "bad_aux",
+ "missing_aux",
+ "literal_aux",
+ "bad_version",
+ "bad_cnr",
+ "extra_input",
+ "extra_output",
+ "bad_type",
+ "wildcard",
+ "union",
+ "mode",
+ "bool_mode",
+ "custom_serializer",
+ "custom_properties",
+ "custom_binding",
+ "bad_slot_name",
+ "bad_reciprocal",
+ "dangling",
+ "bool_slot",
+ "bool_link",
+ "wrong_edge_type",
+ "physical_cycle",
+ "logical_cycle",
+ "unused_bad_get",
+ "unused_bad_set",
+ "nested",
+ "uuid",
+ "ue_edges",
+ ],
+)
+def test_fail_closed_mutations_including_unused_branches(mutation):
+ g = synthetic()
+ s = g["nodes"][1]
+ get = g["nodes"][2]
+ if mutation == "duplicate":
+ extra = copy.deepcopy(s)
+ extra["id"] = 22
+ extra["inputs"][0]["link"] = None
+ g["nodes"].append(extra)
+ elif mutation == "missing_set":
+ s["widgets_values"] = ["other"]
+ elif mutation == "empty":
+ get["widgets_values"] = [""]
+ elif mutation == "bad_name":
+ get["widgets_values"] = [True]
+ elif mutation == "extra_widget":
+ get["widgets_values"].append("extra")
+ elif mutation == "mapping_widget":
+ get["widgets_values"] = {"Constant": "图片"}
+ elif mutation == "bad_aux":
+ s["properties"]["aux_id"] = "rgthree/rgthree-comfy"
+ elif mutation == "missing_aux":
+ s["properties"].pop("aux_id")
+ elif mutation == "literal_aux":
+ s["properties"]["aux_id"] = "SetNode"
+ elif mutation == "bad_version":
+ s["properties"]["ver"] = "1.0.0"
+ elif mutation == "bad_cnr":
+ s["properties"]["cnr_id"] = "other"
+ elif mutation == "extra_input":
+ get["inputs"] = [{"name": "IMAGE", "type": "IMAGE", "link": None}]
+ elif mutation == "extra_output":
+ get["outputs"].append(copy.deepcopy(get["outputs"][0]))
+ elif mutation == "bad_type":
+ get["outputs"][0]["type"] = "FLOAT"
+ g["links"][1][5] = "FLOAT"
+ g["nodes"][3]["inputs"][0]["type"] = "FLOAT"
+ elif mutation in ("wildcard", "union"):
+ s["outputs"][0]["type"] = "*" if mutation == "wildcard" else "IMAGE,MASK"
+ elif mutation == "mode":
+ get["mode"] = 4
+ elif mutation == "bool_mode":
+ get["mode"] = False
+ elif mutation == "custom_serializer":
+ get["serializeValue"] = "override"
+ elif mutation == "custom_properties":
+ s["properties"]["getInputLink"] = "override"
+ elif mutation == "custom_binding":
+ s["properties"]["ue_properties"] = {"widget_ue_connectable": {"Constant": True}}
+ elif mutation == "bad_slot_name":
+ s["inputs"][0]["name"] = "other"
+ elif mutation == "bad_reciprocal":
+ g["nodes"][0]["outputs"][0]["links"] = []
+ elif mutation == "dangling":
+ g["links"][0][1] = 999
+ elif mutation == "bool_slot":
+ g["links"][0][2] = False
+ elif mutation == "bool_link":
+ g["links"][0][0] = True
+ elif mutation == "wrong_edge_type":
+ g["links"][0][5] = "MASK"
+ elif mutation in ("physical_cycle", "logical_cycle"):
+ g["nodes"][0]["outputs"][0]["links"] = []
+ g["links"].pop(0)
+ connect(g, 1, 2 if mutation == "physical_cycle" else 3, 0, 2, 0)
+ elif mutation == "unused_bad_get":
+ g["nodes"].append(virtual(99, "GetNode", "missing"))
+ elif mutation == "unused_bad_set":
+ g["nodes"].append(virtual(99, "SetNode", "unused"))
+ elif mutation == "nested":
+ g["definitions"] = {"subgraphs": [{"id": "any"}]}
+ elif mutation == "uuid":
+ g["nodes"].append({"id": 88, "type": "e61f4fd0-e251-4d58-bfa4-cf163fa86577"})
+ elif mutation == "ue_edges":
+ g["extra"] = {"ue_links": [1]}
+ result = convert_reference(g, PROFILE)
+ assert result.prompt is None, mutation
+ assert result.issues, mutation
+
+
+def test_unknown_ordinary_node_blocks_whole_graph_with_reference_trace_retained():
+ g = synthetic()
+ g["nodes"][0]["type"] = "UnknownImageProducer"
+ result = convert_reference(g, PROFILE)
+ assert result.prompt is None
+ assert result.virtual_resolutions[0]["endpoint"] == ["1", 0]
+ assert any(i["code"] == "reference_node_unsupported" for i in result.issues)
+
+
+def test_ambiguous_provider_trace_is_explicitly_untrusted():
+ g = synthetic()
+ g["nodes"][1]["properties"]["aux_id"] = "SetNode"
+ result = convert_reference(g, PROFILE)
+ assert result.prompt is None and result.diagnostic_graph is None
+ trace = result.virtual_resolutions[0]
+ assert trace["endpoint"] == ["1", 0]
+ assert trace["authority"] == "literal_topology_only" and trace["binding_rejections"]
+
+
+def test_wrong_frontend_missing_policy_and_profile_inventory():
+ p1486 = list(SETGET_PROFILES)[1]
+ assert convert_reference(synthetic(), p1486).prompt is None
+ for v in ["1.48.7", "1.53.6", "1.37.11-other"]:
+ g = synthetic()
+ g["extra"] = {"frontendVersion": v}
+ assert convert_reference(g, PROFILE).prompt is None
+ assert len(audit.REFERENCE_PROFILES) == 20
+
+
+@pytest.mark.parametrize("profile", SETGET_PROFILES)
+def test_vhs_composition_preserves_nonzero_audio_slot_and_exact_commits(profile):
+ prefix = "example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/"
+ source = json.loads((REPO / (prefix + "多视频合成分屏展示.json")).read_bytes())
+ load = next(n for n in source["nodes"] if n["id"] == 17)
+ source = json.loads(
+ (
+ REPO
+ / (
+ "example_ComfyUI_workflows/4-视频生成/Minimax-h3/"
+ "Minimax_H3_T8双时钟采样_参考生视频-8步高质量极速版.json"
+ )
+ ).read_bytes()
+ )
+ combine = next(n for n in source["nodes"] if n["id"] == 12)
+ for n in (load, combine):
+ n.pop("widgets_values_named", None)
+ for s in n["inputs"]:
+ s["link"] = None
+ for s in n["outputs"]:
+ s["links"] = []
+ graph = {
+ "nodes": [
+ load,
+ combine,
+ virtual(900, "SetNode", "audio", "AUDIO"),
+ virtual(901, "GetNode", "audio", "AUDIO"),
+ ],
+ "links": [],
+ "extra": {"frontendVersion": SETGET_PROFILES[profile]},
+ }
+ connect(graph, 1, 17, 0, 12, 0)
+ connect(graph, 2, 17, 2, 900, 0, "AUDIO")
+ connect(graph, 3, 901, 0, 12, 1, "AUDIO")
+ result = convert_reference(graph, profile)
+ assert result.prompt is not None, result.issues
+ assert result.prompt["12"]["inputs"]["audio"] == ["17", 2]
+ assert result.prompt["12"]["inputs"]["images"] == ["17", 0]
+ assert result.prompt["17"]["inputs"]["force_rate"] == 16
+ load["widgets_values"]["force_rate"] = 20
+ assert convert_reference(graph, profile).prompt["17"]["inputs"]["force_rate"] == 20
+ load["properties"]["ver"] = "1.7.9"
+ assert convert_reference(graph, profile).prompt is None
+
+
+@pytest.mark.parametrize(
+ "mutation", ["reroute_type", "ordinary_override", "ordinary_mode", "ordinary_cycle"]
+)
+def test_combined_structure_rejects_other_graph_overrides_and_cycles(mutation):
+ g = synthetic()
+ if mutation == "reroute_type":
+ g["nodes"][1] = {
+ "id": 2,
+ "type": "Reroute",
+ "widgets_values": [],
+ "inputs": [{"name": "", "type": "IMAGE", "link": 1}],
+ "outputs": [{"type": "MASK", "links": []}],
+ }
+ elif mutation == "ordinary_override":
+ g["nodes"][0]["resolveOutput"] = "custom"
+ elif mutation == "ordinary_mode":
+ g["nodes"][0]["mode"] = False
+ else:
+ # Ordinary producer feeds Set, Get feeds the same producer input.
+ g["nodes"][0]["inputs"] = [{"name": "images", "type": "IMAGE", "link": None}]
+ connect(g, 3, 3, 0, 1, 0)
+ assert convert_reference(g, PROFILE).prompt is None
+
+
+def test_historical_18_profiles_attempts_gaps_and_six_comparisons_unchanged():
+ old = json.loads((REPO / "docs/hel-892/vhs-evidence/library.json").read_bytes())
+ baseline = tuple(p for p in audit.REFERENCE_PROFILES if p not in SETGET_PROFILES)
+ now = audit.audit_library(REPO, baseline_profiles=baseline)
+ actual_old = audit.audit_library(REPO, baseline)
+ assert len(baseline) == 18
+ assert actual_old["gap_groups"] == old["gap_groups"]
+ for historical, previous, current in zip(old["cases"], actual_old["cases"], now["cases"]):
+ assert historical["source_path"] == previous["source_path"] == current["source_path"]
+ assert historical["attempts"] == previous["attempts"] == current["attempts"][:18]
+ assert (
+ historical.get("comparisons")
+ == previous.get("comparisons")
+ == current.get("comparisons")
+ )
+ assert now["coverage_delta"]["baseline_profiles"] == list(baseline)
+ assert audit.audit(REPO, "case04-batch-reference") == json.loads(
+ (REPO / "docs/hel-892/media-evidence/protected-six-cases.json").read_bytes()
+ )
diff --git a/calliope-backend/tests/test_vhs_reference.py b/calliope-backend/tests/test_vhs_reference.py
index 20d016da..42a0963a 100644
--- a/calliope-backend/tests/test_vhs_reference.py
+++ b/calliope-backend/tests/test_vhs_reference.py
@@ -285,9 +285,13 @@ def test_real_five_load_instances_are_distinct_and_modes_not_dropped():
def test_old_sixteen_attempts_gaps_candidates_and_six_comparisons_protected():
old = json.loads((REPO / "docs/hel-892/crop-split-evidence/library.json").read_bytes())
- profiles = tuple(p for p in audit.REFERENCE_PROFILES if p not in VHS_PROFILES)
+ # Freeze this batch's 18-profile history; Set/Get has separate current protection.
+ historical_profiles = tuple(
+ p for p in audit.REFERENCE_PROFILES if p not in audit.SETGET_PROFILES
+ )
+ profiles = tuple(p for p in historical_profiles if p not in VHS_PROFILES)
baseline = audit.audit_library(REPO, profiles)
- now = audit.audit_library(REPO, baseline_profiles=profiles)
+ now = audit.audit_library(REPO, historical_profiles, baseline_profiles=profiles)
assert len(profiles) == 16 and len(now["profiles"]) == 18
assert old["gap_groups"] == baseline["gap_groups"]
for previous, before, after in zip(old["cases"], baseline["cases"], now["cases"]):
diff --git a/docs/hel-892/setget-reference/1.37.11__LICENSE b/docs/hel-892/setget-reference/1.37.11__LICENSE
new file mode 100644
index 00000000..f288702d
--- /dev/null
+++ b/docs/hel-892/setget-reference/1.37.11__LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/docs/hel-892/setget-reference/1.37.11__build__plugins__comfyAPIPlugin.ts b/docs/hel-892/setget-reference/1.37.11__build__plugins__comfyAPIPlugin.ts
new file mode 100644
index 00000000..6441dd78
--- /dev/null
+++ b/docs/hel-892/setget-reference/1.37.11__build__plugins__comfyAPIPlugin.ts
@@ -0,0 +1,118 @@
+import path from 'path'
+import type { Plugin } from 'vite'
+
+interface ShimResult {
+ code: string
+ exports: string[]
+}
+
+const SKIP_WARNING_FILES = new Set(['scripts/app', 'scripts/api'])
+
+/** Files that will be removed in v1.34 */
+const DEPRECATED_FILES = ['scripts/ui', 'extensions/core/groupNode'] as const
+
+function getWarningMessage(
+ fileKey: string,
+ shimFileName: string
+): string | null {
+ if (SKIP_WARNING_FILES.has(fileKey)) {
+ return null
+ }
+
+ const isDeprecated = DEPRECATED_FILES.some((deprecatedPath) =>
+ fileKey.startsWith(deprecatedPath)
+ )
+
+ if (isDeprecated) {
+ return `[ComfyUI Deprecated] Importing from "${shimFileName}" is deprecated and will be removed in v1.34.`
+ }
+
+ return `[ComfyUI Notice] "${shimFileName}" is an internal module, not part of the public API. Future updates may break this import.`
+}
+
+function isLegacyFile(id: string): boolean {
+ return (
+ id.endsWith('.ts') &&
+ (id.includes('src/extensions/core') || id.includes('src/scripts'))
+ )
+}
+
+function transformExports(code: string, id: string): ShimResult {
+ const moduleName = getModuleName(id)
+ const exports: string[] = []
+ let newCode = code
+
+ // Regex to match different types of exports
+ const regex =
+ /export\s+(const|let|var|function|class|async function)\s+([a-zA-Z$_][a-zA-Z\d$_]*)(\s|\()/g
+ let match
+
+ while ((match = regex.exec(code)) !== null) {
+ const name = match[2]
+ // All exports should be bind to the window object as new API endpoint.
+ if (exports.length == 0) {
+ newCode += `\nwindow.comfyAPI = window.comfyAPI || {};`
+ newCode += `\nwindow.comfyAPI.${moduleName} = window.comfyAPI.${moduleName} || {};`
+ }
+ newCode += `\nwindow.comfyAPI.${moduleName}.${name} = ${name};`
+ exports.push(
+ `export const ${name} = window.comfyAPI.${moduleName}.${name};\n`
+ )
+ }
+
+ return {
+ code: newCode,
+ exports
+ }
+}
+
+function getModuleName(id: string): string {
+ // Simple example to derive a module name from the file path
+ const parts = id.split('/')
+ const fileName = parts[parts.length - 1]
+ return fileName.replace(/\.\w+$/, '') // Remove file extension
+}
+
+export function comfyAPIPlugin(isDev: boolean): Plugin {
+ return {
+ name: 'comfy-api-plugin',
+ transform(code: string, id: string) {
+ if (isDev) return null
+
+ if (isLegacyFile(id)) {
+ const result = transformExports(code, id)
+
+ if (result.exports.length > 0) {
+ const projectRoot = process.cwd()
+ const relativePath = path
+ .relative(path.join(projectRoot, 'src'), id)
+ .replace(/\\/g, '/')
+ const shimFileName = relativePath.replace(/\.ts$/, '.js')
+
+ let shimContent = `// Shim for ${relativePath}\n`
+
+ const fileKey = relativePath.replace(/\.ts$/, '')
+ const warningMessage = getWarningMessage(fileKey, shimFileName)
+
+ if (warningMessage) {
+ // It will only display once because it is at the root of the file.
+ shimContent += `console.warn('${warningMessage}');\n`
+ }
+
+ shimContent += result.exports.join('')
+
+ this.emitFile({
+ type: 'asset',
+ fileName: shimFileName,
+ source: shimContent
+ })
+ }
+
+ return {
+ code: result.code,
+ map: null // If you're not modifying the source map, return null
+ }
+ }
+ }
+ }
+}
diff --git a/docs/hel-892/setget-reference/1.37.11__src__config__comfyApi.ts b/docs/hel-892/setget-reference/1.37.11__src__config__comfyApi.ts
new file mode 100644
index 00000000..8efd651b
--- /dev/null
+++ b/docs/hel-892/setget-reference/1.37.11__src__config__comfyApi.ts
@@ -0,0 +1,43 @@
+import { isCloud } from '@/platform/distribution/types'
+import {
+ configValueOrDefault,
+ remoteConfig
+} from '@/platform/remoteConfig/remoteConfig'
+
+const PROD_API_BASE_URL = 'https://api.comfy.org'
+const STAGING_API_BASE_URL = 'https://stagingapi.comfy.org'
+
+const PROD_PLATFORM_BASE_URL = 'https://platform.comfy.org'
+const STAGING_PLATFORM_BASE_URL = 'https://stagingplatform.comfy.org'
+
+const BUILD_TIME_API_BASE_URL = __USE_PROD_CONFIG__
+ ? PROD_API_BASE_URL
+ : STAGING_API_BASE_URL
+
+const BUILD_TIME_PLATFORM_BASE_URL = __USE_PROD_CONFIG__
+ ? PROD_PLATFORM_BASE_URL
+ : STAGING_PLATFORM_BASE_URL
+
+export function getComfyApiBaseUrl(): string {
+ if (!isCloud) {
+ return BUILD_TIME_API_BASE_URL
+ }
+
+ return configValueOrDefault(
+ remoteConfig.value,
+ 'comfy_api_base_url',
+ BUILD_TIME_API_BASE_URL
+ )
+}
+
+export function getComfyPlatformBaseUrl(): string {
+ if (!isCloud) {
+ return BUILD_TIME_PLATFORM_BASE_URL
+ }
+
+ return configValueOrDefault(
+ remoteConfig.value,
+ 'comfy_platform_base_url',
+ BUILD_TIME_PLATFORM_BASE_URL
+ )
+}
diff --git a/docs/hel-892/setget-reference/1.37.11__src__lib__litegraph__src__LGraphNode.ts b/docs/hel-892/setget-reference/1.37.11__src__lib__litegraph__src__LGraphNode.ts
new file mode 100644
index 00000000..0ca41a73
--- /dev/null
+++ b/docs/hel-892/setget-reference/1.37.11__src__lib__litegraph__src__LGraphNode.ts
@@ -0,0 +1,4198 @@
+import { LGraphNodeProperties } from '@/lib/litegraph/src/LGraphNodeProperties'
+import {
+ calculateInputSlotPos,
+ calculateInputSlotPosFromSlot,
+ calculateOutputSlotPos,
+ getSlotPosition
+} from '@/renderer/core/canvas/litegraph/slotCalculations'
+import type { SlotPositionContext } from '@/renderer/core/canvas/litegraph/slotCalculations'
+import { useLayoutMutations } from '@/renderer/core/layout/operations/layoutMutations'
+import { LayoutSource } from '@/renderer/core/layout/types'
+import { adjustColor } from '@/utils/colorUtil'
+import type { ColorAdjustOptions } from '@/utils/colorUtil'
+import { commonType, toClass } from '@/lib/litegraph/src/utils/type'
+
+import { SUBGRAPH_OUTPUT_ID } from '@/lib/litegraph/src/constants'
+import type { DragAndScale } from './DragAndScale'
+import type { LGraph } from './LGraph'
+import { BadgePosition, LGraphBadge } from './LGraphBadge'
+import { LGraphButton } from './LGraphButton'
+import type { LGraphButtonOptions } from './LGraphButton'
+import { LGraphCanvas } from './LGraphCanvas'
+import { LLink } from './LLink'
+import type { Reroute, RerouteId } from './Reroute'
+import { getNodeInputOnPos, getNodeOutputOnPos } from './canvas/measureSlots'
+import type { IDrawBoundingOptions } from './draw'
+import { NullGraphError } from './infrastructure/NullGraphError'
+import type { ReadOnlyRectangle } from './infrastructure/Rectangle'
+import { Rectangle } from './infrastructure/Rectangle'
+import type {
+ ColorOption,
+ CompassCorners,
+ DefaultConnectionColors,
+ Dictionary,
+ IColorable,
+ IContextMenuValue,
+ IFoundSlot,
+ INodeFlags,
+ INodeInputSlot,
+ INodeOutputSlot,
+ INodeSlot,
+ INodeSlotContextItem,
+ IPinnable,
+ ISlotType,
+ Point,
+ Positionable,
+ ReadOnlyRect,
+ Rect,
+ Size
+} from './interfaces'
+import { LiteGraph, Subgraph } from './litegraph'
+import type { LGraphNodeConstructor, SubgraphNode } from './litegraph'
+import {
+ createBounds,
+ isInRect,
+ isInRectangle,
+ isPointInRect,
+ snapPoint
+} from './measure'
+import { NodeInputSlot } from './node/NodeInputSlot'
+import { NodeOutputSlot } from './node/NodeOutputSlot'
+import {
+ inputAsSerialisable,
+ isINodeInputSlot,
+ isWidgetInputSlot,
+ outputAsSerialisable
+} from './node/slotUtils'
+import type { SubgraphInputNode } from './subgraph/SubgraphInputNode'
+import type { SubgraphOutputNode } from './subgraph/SubgraphOutputNode'
+import type { NodeLike } from './types/NodeLike'
+import type { CanvasPointerEvent } from './types/events'
+import {
+ LGraphEventMode,
+ NodeSlotType,
+ RenderShape,
+ TitleMode
+} from './types/globalEnums'
+import type { ISerialisedNode, SubgraphIO } from './types/serialisation'
+import type {
+ IBaseWidget,
+ IWidgetOptions,
+ TWidgetType,
+ TWidgetValue
+} from './types/widgets'
+import { findFreeSlotOfType } from './utils/collections'
+import { warnDeprecated } from './utils/feedback'
+import { distributeSpace } from './utils/spaceDistribution'
+import { truncateText } from './utils/textUtils'
+import { BaseWidget } from './widgets/BaseWidget'
+import { toConcreteWidget } from './widgets/widgetMap'
+import type { WidgetTypeMap } from './widgets/widgetMap'
+
+// #region Types
+
+export type NodeId = number | string
+
+export type NodeProperty = string | number | boolean | object
+
+interface INodePropertyInfo {
+ name: string
+ type?: string
+ default_value: NodeProperty | undefined
+}
+
+interface IMouseOverData {
+ inputId?: number
+ outputId?: number
+ overWidget?: IBaseWidget
+}
+
+interface ConnectByTypeOptions {
+ /** @deprecated Events */
+ createEventInCase?: boolean
+ /** Allow our wildcard slot to connect to typed slots on remote node. Default: true */
+ wildcardToTyped?: boolean
+ /** Allow our typed slot to connect to wildcard slots on remote node. Default: true */
+ typedToWildcard?: boolean
+ /** The {@link Reroute.id} that the connection is being dragged from. */
+ afterRerouteId?: RerouteId
+}
+
+/** Internal type used for type safety when implementing generic checks for inputs & outputs */
+interface IGenericLinkOrLinks {
+ links?: INodeOutputSlot['links']
+ link?: INodeInputSlot['link']
+}
+
+interface FindFreeSlotOptions {
+ /** Slots matching these types will be ignored. Default: [] */
+ typesNotAccepted?: ISlotType[]
+ /** If true, the slot itself is returned instead of the index. Default: false */
+ returnObj?: boolean
+}
+
+interface DrawSlotsOptions {
+ fromSlot?: INodeInputSlot | INodeOutputSlot
+ colorContext: DefaultConnectionColors
+ editorAlpha: number
+ lowQuality: boolean
+}
+
+interface DrawWidgetsOptions {
+ lowQuality?: boolean
+ editorAlpha?: number
+}
+
+interface DrawTitleOptions {
+ scale: number
+ title_height?: number
+ low_quality?: boolean
+}
+
+interface DrawTitleTextOptions extends DrawTitleOptions {
+ default_title_color: string
+}
+
+export interface DrawTitleBoxOptions extends DrawTitleOptions {
+ box_size?: number
+}
+
+/*
+title: string
+pos: [x,y]
+size: [x,y]
+
+input|output: every connection
+ + { name:string, type:string, pos: [x,y]=Optional, direction: "input"|"output", links: Array });
+
+general properties:
+ + clip_area: if you render outside the node, it will be clipped
+ + unsafe_execution: not allowed for safe execution
+ + skip_repeated_outputs: when adding new outputs, it won't show if there is one already connected
+ + resizable: if set to false it won't be resizable with the mouse
+ + widgets_start_y: widgets start at y distance from the top of the node
+
+flags object:
+ + collapsed: if it is collapsed
+
+supported callbacks:
+ + onAdded: when added to graph (warning: this is called BEFORE the node is configured when loading)
+ + onRemoved: when removed from graph
+ + onStart: when the graph starts playing
+ + onStop: when the graph stops playing
+ + onDrawForeground: render the inside widgets inside the node
+ + onDrawBackground: render the background area inside the node (only in edit mode)
+ + onMouseDown
+ + onMouseMove
+ + onMouseUp
+ + onMouseEnter
+ + onMouseLeave
+ + onExecute: execute the node
+ + onPropertyChanged: when a property is changed in the panel (return true to skip default behaviour)
+ + onGetInputs: returns an array of possible inputs
+ + onGetOutputs: returns an array of possible outputs
+ + onBounding: in case this node has a bigger bounding than the node itself (the callback receives the bounding as [x,y,w,h])
+ + onDblClick: double clicked in the node
+ + onNodeTitleDblClick: double clicked in the node title
+ + onInputDblClick: input slot double clicked (can be used to automatically create a node connected)
+ + onOutputDblClick: output slot double clicked (can be used to automatically create a node connected)
+ + onConfigure: called after the node has been configured
+ + onSerialize: to add extra info when serializing (the callback receives the object that should be filled with the data)
+ + onSelected
+ + onDeselected
+ + onDropItem : DOM item dropped over the node
+ + onDropFile : file dropped over the node
+ + onConnectInput : if returns false the incoming connection will be canceled
+ + onConnectionsChange : a connection changed (new one or removed) (NodeSlotType.INPUT or NodeSlotType.OUTPUT, slot, true if connected, link_info, input_info )
+ + onAction: action slot triggered
+ + getExtraMenuOptions: to add option to context menu
+*/
+
+export interface LGraphNode {
+ constructor: LGraphNodeConstructor
+}
+
+// #endregion Types
+
+/**
+ * Base class for all nodes
+ * @param title a name for the node
+ * @param type a type for the node
+ */
+
+export class LGraphNode
+ implements NodeLike, Positionable, IPinnable, IColorable
+{
+ // Static properties used by dynamic child classes
+ static title?: string
+ static MAX_CONSOLE?: number
+ static type?: string
+ static category?: string
+ static description?: string
+ static filter?: string
+ static skip_list?: boolean
+
+ static resizeHandleSize = 15
+ static resizeEdgeSize = 5
+
+ /** Default setting for {@link LGraphNode.connectInputToOutput}. @see {@link INodeFlags.keepAllLinksOnBypass} */
+ static keepAllLinksOnBypass: boolean = false
+
+ /** The title text of the node. */
+ title: string
+ /**
+ * The font style used to render the node's title text.
+ */
+ get titleFontStyle(): string {
+ return `${LiteGraph.NODE_TEXT_SIZE}px ${LiteGraph.NODE_FONT}`
+ }
+
+ get innerFontStyle(): string {
+ return `normal ${LiteGraph.NODE_SUBTEXT_SIZE}px ${LiteGraph.NODE_FONT}`
+ }
+
+ get displayType(): string {
+ return this.type
+ }
+
+ graph: LGraph | Subgraph | null = null
+ id: NodeId
+ type: string = ''
+ inputs: INodeInputSlot[] = []
+ outputs: INodeOutputSlot[] = []
+
+ #concreteInputs: NodeInputSlot[] = []
+ #concreteOutputs: NodeOutputSlot[] = []
+
+ properties: Dictionary = {}
+ properties_info: INodePropertyInfo[] = []
+ flags: INodeFlags = {}
+ widgets?: IBaseWidget[]
+
+ /** Property manager for this node */
+ changeTracker: LGraphNodeProperties
+
+ /**
+ * The amount of space available for widgets to grow into.
+ * @see {@link layoutWidgets}
+ */
+ freeWidgetSpace?: number
+
+ locked?: boolean
+
+ /** Execution order, automatically computed during run @see {@link LGraph.computeExecutionOrder} */
+ order: number = 0
+ mode: LGraphEventMode = LGraphEventMode.ALWAYS
+ last_serialization?: ISerialisedNode
+ serialize_widgets?: boolean
+ /**
+ * The overridden fg color used to render the node.
+ * @see {@link renderingColor}
+ */
+ color?: string
+ /**
+ * The overridden bg color used to render the node.
+ * @see {@link renderingBgColor}
+ */
+ bgcolor?: string
+ /**
+ * The overridden box color used to render the node.
+ * @see {@link renderingBoxColor}
+ */
+ boxcolor?: string
+
+ /** The fg color used to render the node. */
+ get renderingColor(): string {
+ const baseColor =
+ this.color || this.constructor.color || LiteGraph.NODE_DEFAULT_COLOR
+ return adjustColor(baseColor, { lightness: LiteGraph.nodeLightness })
+ }
+
+ /** The bg color used to render the node. */
+ get renderingBgColor(): string {
+ const baseBgColor =
+ this.bgcolor || this.constructor.bgcolor || LiteGraph.NODE_DEFAULT_BGCOLOR
+ const adjustments: ColorAdjustOptions = {
+ opacity: LiteGraph.nodeOpacity,
+ lightness: LiteGraph.nodeLightness
+ }
+
+ return adjustColor(
+ this.mode === LGraphEventMode.BYPASS
+ ? LiteGraph.NODE_DEFAULT_BYPASS_COLOR
+ : baseBgColor,
+ adjustments
+ )
+ }
+
+ /** The box color used to render the node. */
+ get renderingBoxColor(): string {
+ if (this.boxcolor) return this.boxcolor
+
+ if (LiteGraph.node_box_coloured_when_on) {
+ if (this.action_triggered) return '#FFF'
+ if (this.execute_triggered) return '#AAA'
+ }
+
+ if (LiteGraph.node_box_coloured_by_mode) {
+ const modeColour =
+ LiteGraph.NODE_MODES_COLORS[this.mode ?? LGraphEventMode.ALWAYS]
+ if (modeColour) return modeColour
+ }
+ return LiteGraph.NODE_DEFAULT_BOXCOLOR
+ }
+
+ /** @inheritdoc {@link IColorable.setColorOption} */
+ setColorOption(colorOption: ColorOption | null): void {
+ if (colorOption == null) {
+ this.color = undefined
+ this.bgcolor = undefined
+ } else {
+ this.color = colorOption.color
+ this.bgcolor = colorOption.bgcolor
+ }
+ }
+
+ /** @inheritdoc {@link IColorable.getColorOption} */
+ getColorOption(): ColorOption | null {
+ return (
+ Object.values(LGraphCanvas.node_colors).find(
+ (colorOption) =>
+ colorOption.color === this.color &&
+ colorOption.bgcolor === this.bgcolor
+ ) ?? null
+ )
+ }
+
+ /**
+ * The stroke styles that should be applied to the node.
+ */
+ strokeStyles: Record<
+ string,
+ (this: LGraphNode) => IDrawBoundingOptions | undefined
+ >
+
+ /**
+ * The progress of node execution. Used to render a progress bar. Value between 0 and 1.
+ */
+ progress?: number
+
+ exec_version?: number
+ action_call?: string
+ execute_triggered?: number
+ action_triggered?: number
+ widgets_up?: boolean
+ widgets_start_y?: number
+ lostFocusAt?: number
+ gotFocusAt?: number
+ badges: (LGraphBadge | (() => LGraphBadge))[] = []
+ title_buttons: LGraphButton[] = []
+ badgePosition: BadgePosition = BadgePosition.TopLeft
+ onOutputRemoved?(this: LGraphNode, slot: number): void
+ onInputRemoved?(this: LGraphNode, slot: number, input: INodeInputSlot): void
+ /**
+ * The width of the node when collapsed.
+ * Updated by {@link LGraphCanvas.drawNode}
+ */
+ _collapsed_width?: number
+ /**
+ * Called once at the start of every frame. Caller may change the values in {@link out}, which will be reflected in {@link boundingRect}.
+ * WARNING: Making changes to boundingRect via onBounding is poorly supported, and will likely result in strange behaviour.
+ */
+ onBounding?(this: LGraphNode, out: Rect): void
+ console?: string[]
+ _level?: number
+ _shape?: RenderShape
+ mouseOver?: IMouseOverData
+ redraw_on_mouse?: boolean
+ resizable?: boolean
+ clonable?: boolean
+ _relative_id?: number
+ clip_area?: boolean
+ ignore_remove?: boolean
+ has_errors?: boolean
+ removable?: boolean
+ block_delete?: boolean
+ selected?: boolean
+ showAdvanced?: boolean
+
+ declare comfyDynamic?: Record
+ declare comfyClass?: string
+ declare isVirtualNode?: boolean
+ applyToGraph?(extraLinks?: LLink[]): void
+
+ isSubgraphNode(): this is SubgraphNode {
+ return false
+ }
+
+ /** @inheritdoc {@link renderArea} */
+ #renderArea = new Rectangle()
+ /**
+ * Rect describing the node area, including shadows and any protrusions.
+ * Determines if the node is visible. Calculated once at the start of every frame.
+ */
+ get renderArea(): ReadOnlyRect {
+ return this.#renderArea
+ }
+
+ /** @inheritdoc {@link boundingRect} */
+ #boundingRect: Rectangle = new Rectangle()
+ /**
+ * Cached node position & area as `x, y, width, height`. Includes changes made by {@link onBounding}, if present.
+ *
+ * Determines the node hitbox and other rendering effects. Calculated once at the start of every frame.
+ */
+ get boundingRect(): ReadOnlyRectangle {
+ return this.#boundingRect
+ }
+
+ /** The offset from {@link pos} to the top-left of {@link boundingRect}. */
+ get boundingOffset(): Readonly {
+ const {
+ pos: [posX, posY],
+ boundingRect: [bX, bY]
+ } = this
+ return [posX - bX, posY - bY]
+ }
+
+ /** {@link pos} and {@link size} values are backed by this {@link Rectangle}. */
+ _posSize = new Rectangle()
+ _pos: Point = this._posSize.pos
+ _size: Size = this._posSize.size
+
+ public get pos() {
+ return this._pos
+ }
+
+ /** Node position does not necessarily correlate to the top-left corner. */
+ public set pos(value) {
+ if (!value || value.length < 2) return
+
+ this._pos[0] = value[0]
+ this._pos[1] = value[1]
+ }
+
+ public get size() {
+ return this._size
+ }
+
+ public set size(value) {
+ if (!value || value.length < 2) return
+
+ this._size[0] = value[0]
+ this._size[1] = value[1]
+ }
+
+ /**
+ * The size of the node used for rendering.
+ */
+ get renderingSize(): Size {
+ return this.flags.collapsed ? [this._collapsed_width ?? 0, 0] : this._size
+ }
+
+ get shape(): RenderShape | undefined {
+ return this._shape
+ }
+
+ set shape(v: RenderShape | 'default' | 'box' | 'round' | 'circle' | 'card') {
+ const oldValue = this._shape
+ switch (v) {
+ case 'default':
+ this._shape = undefined
+ break
+ case 'box':
+ this._shape = RenderShape.BOX
+ break
+ case 'round':
+ this._shape = RenderShape.ROUND
+ break
+ case 'circle':
+ this._shape = RenderShape.CIRCLE
+ break
+ case 'card':
+ this._shape = RenderShape.CARD
+ break
+ default:
+ this._shape = v
+ }
+ if (oldValue !== this._shape) {
+ this.graph?.trigger('node:property:changed', {
+ nodeId: this.id,
+ property: 'shape',
+ oldValue,
+ newValue: this._shape
+ })
+ }
+ }
+
+ /**
+ * The shape of the node used for rendering. @see {@link RenderShape}
+ */
+ get renderingShape(): RenderShape {
+ return this._shape || this.constructor.shape || LiteGraph.NODE_DEFAULT_SHAPE
+ }
+
+ public get is_selected(): boolean | undefined {
+ return this.selected
+ }
+
+ public set is_selected(value: boolean) {
+ this.selected = value
+ }
+
+ public get title_mode(): TitleMode {
+ return this.constructor.title_mode ?? TitleMode.NORMAL_TITLE
+ }
+
+ onConnectInput?(
+ this: LGraphNode,
+ target_slot: number,
+ type: unknown,
+ output: INodeOutputSlot | SubgraphIO,
+ node: LGraphNode | SubgraphInputNode,
+ slot: number
+ ): boolean
+ onConnectOutput?(
+ this: LGraphNode,
+ slot: number,
+ type: unknown,
+ input: INodeInputSlot | SubgraphIO,
+ target_node: number | LGraphNode | SubgraphOutputNode,
+ target_slot: number
+ ): boolean
+ onResize?(this: LGraphNode, size: Size): void
+ onPropertyChanged?(
+ this: LGraphNode,
+ name: string,
+ value: unknown,
+ prev_value?: unknown
+ ): boolean
+ /** Called for each connection that is created, updated, or removed. This includes "restored" connections when deserialising. */
+ onConnectionsChange?(
+ this: LGraphNode,
+ type: ISlotType,
+ index: number,
+ isConnected: boolean,
+ link_info: LLink | null | undefined,
+ inputOrOutput: INodeInputSlot | INodeOutputSlot | SubgraphIO
+ ): void
+ onInputAdded?(this: LGraphNode, input: INodeInputSlot): void
+ onOutputAdded?(this: LGraphNode, output: INodeOutputSlot): void
+ onConfigure?(this: LGraphNode, serialisedNode: ISerialisedNode): void
+ onSerialize?(this: LGraphNode, serialised: ISerialisedNode): void
+ onExecute?(
+ this: LGraphNode,
+ param?: unknown,
+ options?: { action_call?: string }
+ ): void
+ onAction?(
+ this: LGraphNode,
+ action: string,
+ param: unknown,
+ options: { action_call?: string }
+ ): void
+ onDrawBackground?(this: LGraphNode, ctx: CanvasRenderingContext2D): void
+ onNodeCreated?(this: LGraphNode): void
+ /**
+ * Callback invoked by {@link connect} to override the target slot index.
+ * Its return value overrides the target index selection.
+ * @param target_slot The current input slot index
+ * @param requested_slot The originally requested slot index - could be negative, or if using (deprecated) name search, a string
+ * @returns {number | null} If a number is returned, the connection will be made to that input index.
+ * If an invalid index or non-number (false, null, NaN etc) is returned, the connection will be cancelled.
+ */
+ onBeforeConnectInput?(
+ this: LGraphNode,
+ target_slot: number,
+ requested_slot?: number | string
+ ): number | false | null
+ onShowCustomPanelInfo?(this: LGraphNode, panel: any): void
+ onAddPropertyToPanel?(this: LGraphNode, pName: string, panel: any): boolean
+ onWidgetChanged?(
+ this: LGraphNode,
+ name: string,
+ value: unknown,
+ old_value: unknown,
+ w: IBaseWidget
+ ): void
+ onDeselected?(this: LGraphNode): void
+ onKeyUp?(this: LGraphNode, e: KeyboardEvent): void
+ onKeyDown?(this: LGraphNode, e: KeyboardEvent): void
+ onSelected?(this: LGraphNode): void
+ getExtraMenuOptions?(
+ this: LGraphNode,
+ canvas: LGraphCanvas,
+ options: (IContextMenuValue | null)[]
+ ): (IContextMenuValue | null)[]
+ getMenuOptions?(this: LGraphNode, canvas: LGraphCanvas): IContextMenuValue[]
+ onAdded?(this: LGraphNode, graph: LGraph): void
+ onDrawCollapsed?(
+ this: LGraphNode,
+ ctx: CanvasRenderingContext2D,
+ cavnas: LGraphCanvas
+ ): boolean
+ onDrawForeground?(
+ this: LGraphNode,
+ ctx: CanvasRenderingContext2D,
+ canvas: LGraphCanvas,
+ canvasElement: HTMLCanvasElement
+ ): void
+ onMouseLeave?(this: LGraphNode, e: CanvasPointerEvent): void
+ /**
+ * Override the default slot menu options.
+ */
+ getSlotMenuOptions?(this: LGraphNode, slot: IFoundSlot): IContextMenuValue[]
+ /**
+ * Add extra menu options to the slot context menu.
+ */
+ getExtraSlotMenuOptions?(
+ this: LGraphNode,
+ slot: IFoundSlot
+ ): IContextMenuValue[]
+
+ // FIXME: Re-typing
+ onDropItem?(this: LGraphNode, event: Event): boolean
+ onDropData?(
+ this: LGraphNode,
+ data: string | ArrayBuffer,
+ filename: string,
+ file: File
+ ): void
+ onDropFile?(this: LGraphNode, file: File): void
+ onInputClick?(this: LGraphNode, index: number, e: CanvasPointerEvent): void
+ onInputDblClick?(this: LGraphNode, index: number, e: CanvasPointerEvent): void
+ onOutputClick?(this: LGraphNode, index: number, e: CanvasPointerEvent): void
+ onOutputDblClick?(
+ this: LGraphNode,
+ index: number,
+ e: CanvasPointerEvent
+ ): void
+ // TODO: Return type
+ onGetPropertyInfo?(this: LGraphNode, property: string): any
+ onNodeOutputAdd?(this: LGraphNode, value: unknown): void
+ onNodeInputAdd?(this: LGraphNode, value: unknown): void
+ onMenuNodeInputs?(
+ this: LGraphNode,
+ entries: (IContextMenuValue | null)[]
+ ): (IContextMenuValue | null)[]
+ onMenuNodeOutputs?(
+ this: LGraphNode,
+ entries: (IContextMenuValue | null)[]
+ ): (IContextMenuValue | null)[]
+ onMouseUp?(
+ this: LGraphNode,
+ e: CanvasPointerEvent,
+ pos: Point,
+ canvas: LGraphCanvas
+ ): void
+ onMouseEnter?(this: LGraphNode, e: CanvasPointerEvent): void
+ /** Blocks drag if return value is truthy. @param pos Offset from {@link LGraphNode.pos}. */
+ onMouseDown?(
+ this: LGraphNode,
+ e: CanvasPointerEvent,
+ pos: Point,
+ canvas: LGraphCanvas
+ ): boolean
+ /** @param pos Offset from {@link LGraphNode.pos}. */
+ onDblClick?(
+ this: LGraphNode,
+ e: CanvasPointerEvent,
+ pos: Point,
+ canvas: LGraphCanvas
+ ): void
+ /** @param pos Offset from {@link LGraphNode.pos}. */
+ onNodeTitleDblClick?(
+ this: LGraphNode,
+ e: CanvasPointerEvent,
+ pos: Point,
+ canvas: LGraphCanvas
+ ): void
+ onDrawTitle?(this: LGraphNode, ctx: CanvasRenderingContext2D): void
+ onDrawTitleText?(
+ this: LGraphNode,
+ ctx: CanvasRenderingContext2D,
+ title_height: number,
+ size: Size,
+ scale: number,
+ title_text_font: string,
+ selected?: boolean
+ ): void
+ onDrawTitleBox?(
+ this: LGraphNode,
+ ctx: CanvasRenderingContext2D,
+ title_height: number,
+ size: Size,
+ scale: number
+ ): void
+ onDrawTitleBar?(
+ this: LGraphNode,
+ ctx: CanvasRenderingContext2D,
+ title_height: number,
+ size: Size,
+ scale: number,
+ fgcolor: string
+ ): void
+ onRemoved?(this: LGraphNode): void
+ onMouseMove?(
+ this: LGraphNode,
+ e: CanvasPointerEvent,
+ pos: Point,
+ arg2: LGraphCanvas
+ ): void
+ onPropertyChange?(this: LGraphNode): void
+ updateOutputData?(this: LGraphNode, origin_slot: number): void
+
+ #getErrorStrokeStyle(this: LGraphNode): IDrawBoundingOptions | undefined {
+ if (this.has_errors) {
+ return {
+ padding: 12,
+ lineWidth: 10,
+ color: LiteGraph.NODE_ERROR_COLOUR
+ }
+ }
+ }
+
+ #getSelectedStrokeStyle(this: LGraphNode): IDrawBoundingOptions | undefined {
+ if (this.selected) {
+ return {
+ padding: this.has_errors ? 20 : undefined
+ }
+ }
+ }
+
+ constructor(title: string, type?: string) {
+ this.id = LiteGraph.use_uuids ? LiteGraph.uuidv4() : -1
+ this.title = title || 'Unnamed'
+ this.type = type ?? ''
+ this.size = [LiteGraph.NODE_WIDTH, 60]
+ this.pos = [10, 10]
+ this.strokeStyles = {
+ error: this.#getErrorStrokeStyle,
+ selected: this.#getSelectedStrokeStyle
+ }
+ // Initialize property manager with tracked properties
+ this.changeTracker = new LGraphNodeProperties(this)
+ }
+
+ /** Internal callback for subgraph nodes. Do not implement externally. */
+ _internalConfigureAfterSlots?(): void
+
+ /**
+ * configure a node from an object containing the serialized info
+ */
+ configure(info: ISerialisedNode): void {
+ if (this.graph) {
+ this.graph._version++
+ }
+ for (const j in info) {
+ if (j == 'properties') {
+ // i don't want to clone properties, I want to reuse the old container
+ for (const k in info.properties) {
+ this.properties[k] = info.properties[k]
+ this.onPropertyChanged?.(k, info.properties[k])
+ }
+ continue
+ }
+
+ // @ts-expect-error #594
+ if (info[j] == null) {
+ continue
+ // @ts-expect-error #594
+ } else if (typeof info[j] == 'object') {
+ // @ts-expect-error #594
+ if (this[j]?.configure) {
+ // @ts-expect-error #594
+ this[j]?.configure(info[j])
+ } else {
+ // @ts-expect-error #594
+ this[j] = LiteGraph.cloneObject(info[j], this[j])
+ }
+ } else {
+ // value
+ // @ts-expect-error #594
+ this[j] = info[j]
+ }
+ }
+
+ if (!info.title) {
+ this.title = this.constructor.title
+ }
+
+ this.inputs ??= []
+ this.inputs = this.inputs.map((input) =>
+ toClass(NodeInputSlot, input, this)
+ )
+ for (const [i, input] of this.inputs.entries()) {
+ const link =
+ this.graph && input.link != null
+ ? this.graph._links.get(input.link)
+ : null
+ this.onConnectionsChange?.(NodeSlotType.INPUT, i, true, link, input)
+ this.onInputAdded?.(input)
+ }
+
+ this.outputs ??= []
+ this.outputs = this.outputs.map((output) =>
+ toClass(NodeOutputSlot, output, this)
+ )
+ for (const [i, output] of this.outputs.entries()) {
+ if (!output.links) continue
+
+ for (const linkId of output.links) {
+ const link = this.graph ? this.graph._links.get(linkId) : null
+ this.onConnectionsChange?.(NodeSlotType.OUTPUT, i, true, link, output)
+ }
+ this.onOutputAdded?.(output)
+ }
+
+ // SubgraphNode callback.
+ this._internalConfigureAfterSlots?.()
+
+ if (this.widgets) {
+ for (const w of this.widgets) {
+ if (!w) continue
+
+ const input = this.inputs.find((i) => i.widget?.name === w.name)
+ if (input?.label) w.label = input.label
+
+ if (
+ w.options?.property &&
+ this.properties[w.options.property] != undefined
+ )
+ w.value = JSON.parse(
+ JSON.stringify(this.properties[w.options.property])
+ )
+ }
+
+ if (info.widgets_values) {
+ let i = 0
+ for (const widget of this.widgets ?? []) {
+ if (widget.serialize === false) continue
+ if (i >= info.widgets_values.length) break
+ widget.value = info.widgets_values[i++]
+ }
+ }
+ }
+
+ // Sync the state of this.resizable.
+ if (this.pinned) this.resizable = false
+
+ this.onConfigure?.(info)
+ }
+
+ /**
+ * serialize the content
+ */
+ serialize(): ISerialisedNode {
+ // create serialization object
+ const o: ISerialisedNode = {
+ id: this.id,
+ type: this.type,
+ pos: [this.pos[0], this.pos[1]],
+ size: [this.size[0], this.size[1]],
+ flags: LiteGraph.cloneObject(this.flags),
+ order: this.order,
+ mode: this.mode,
+ showAdvanced: this.showAdvanced
+ }
+
+ // special case for when there were errors
+ if (this.constructor === LGraphNode && this.last_serialization)
+ return { ...this.last_serialization, mode: o.mode, pos: o.pos }
+
+ if (this.inputs)
+ o.inputs = this.inputs.map((input) => inputAsSerialisable(input))
+ if (this.outputs)
+ // @ts-expect-error - Output serialization type mismatch
+ o.outputs = this.outputs.map((output) => outputAsSerialisable(output))
+
+ if (this.title && this.title != this.constructor.title) o.title = this.title
+
+ if (this.properties) o.properties = LiteGraph.cloneObject(this.properties)
+
+ const { widgets } = this
+ if (widgets && this.serialize_widgets) {
+ o.widgets_values = []
+ for (const [i, widget] of widgets.entries()) {
+ if (widget.serialize === false) continue
+ // @ts-expect-error #595 No-null
+ o.widgets_values[i] = widget ? widget.value : null
+ }
+ }
+
+ if (!o.type && this.constructor.type) o.type = this.constructor.type
+
+ if (this.color) o.color = this.color
+ if (this.bgcolor) o.bgcolor = this.bgcolor
+ if (this.boxcolor) o.boxcolor = this.boxcolor
+ if (this.shape) o.shape = this.shape
+
+ if (this.onSerialize?.(o))
+ console.warn(
+ "node onSerialize shouldn't return anything, data should be stored in the object pass in the first parameter"
+ )
+
+ return o
+ }
+
+ /* Creates a clone of this node */
+ clone(): LGraphNode | null {
+ if (this.type == null) return null
+ const node = LiteGraph.createNode(this.type)
+ if (!node) return null
+
+ // we clone it because serialize returns shared containers
+ const data = LiteGraph.cloneObject(this.serialize())
+ const { inputs, outputs } = data
+
+ // remove links
+ if (inputs) {
+ for (const input of inputs) {
+ input.link = null
+ }
+ }
+
+ if (outputs) {
+ for (const { links } of outputs) {
+ if (links) links.length = 0
+ }
+ }
+
+ // @ts-expect-error Exceptional case: id is removed so that the graph can assign a new one on add.
+ data.id = undefined
+
+ if (LiteGraph.use_uuids) data.id = LiteGraph.uuidv4()
+
+ node.configure(data)
+
+ return node
+ }
+
+ /**
+ * serialize and stringify
+ */
+ toString(): string {
+ return JSON.stringify(this.serialize())
+ }
+
+ /**
+ * get the title string
+ */
+ getTitle(): string {
+ return this.title || this.constructor.title
+ }
+
+ /**
+ * sets the value of a property
+ * @param name
+ * @param value
+ */
+ setProperty(name: string, value: TWidgetValue): void {
+ this.properties ||= {}
+ if (value === this.properties[name]) return
+
+ const prev_value = this.properties[name]
+ this.properties[name] = value
+ // abort change
+ if (this.onPropertyChanged?.(name, value, prev_value) === false)
+ this.properties[name] = prev_value
+
+ if (this.widgets) {
+ for (const w of this.widgets) {
+ if (!w) continue
+
+ if (w.options.property == name) {
+ w.value = value
+ break
+ }
+ }
+ }
+ }
+
+ /**
+ * sets the output data
+ * @param slot
+ * @param data
+ */
+ setOutputData(
+ slot: number,
+ data: number | string | boolean | { toToolTip?(): string }
+ ): void {
+ const { outputs } = this
+ if (!outputs) return
+
+ // this maybe slow and a niche case
+ if (slot == -1 || slot >= outputs.length) return
+
+ const output_info = outputs[slot]
+ if (!output_info) return
+
+ // store data in the output itself in case we want to debug
+ output_info._data = data
+
+ if (!this.graph) throw new NullGraphError()
+
+ // if there are connections, pass the data to the connections
+ const { links } = outputs[slot]
+ if (links) {
+ for (const id of links) {
+ const link = this.graph._links.get(id)
+ if (link) link.data = data
+ }
+ }
+ }
+
+ /**
+ * sets the output data type, useful when you want to be able to overwrite the data type
+ */
+ setOutputDataType(slot: number, type: ISlotType): void {
+ const { outputs } = this
+ if (!outputs || slot == -1 || slot >= outputs.length) return
+
+ const output_info = outputs[slot]
+ if (!output_info) return
+ // store data in the output itself in case we want to debug
+ output_info.type = type
+
+ if (!this.graph) throw new NullGraphError()
+
+ // if there are connections, pass the data to the connections
+ const { links } = outputs[slot]
+ if (links) {
+ for (const id of links) {
+ const link = this.graph._links.get(id)
+ if (link) link.type = type
+ }
+ }
+ }
+
+ /**
+ * Retrieves the input data (data traveling through the connection) from one slot
+ * @param slot
+ * @param force_update if set to true it will force the connected node of this slot to output data into this link
+ * @returns data or if it is not connected returns undefined
+ */
+ getInputData(slot: number, force_update?: boolean): unknown {
+ if (!this.inputs) return
+
+ if (slot >= this.inputs.length || this.inputs[slot].link == null) return
+ if (!this.graph) throw new NullGraphError()
+
+ const link_id = this.inputs[slot].link
+ const link = this.graph._links.get(link_id)
+ // bug: weird case but it happens sometimes
+ if (!link) return null
+
+ if (!force_update) return link.data
+
+ // special case: used to extract data from the incoming connection before the graph has been executed
+ const node = this.graph.getNodeById(link.origin_id)
+ if (!node) return link.data
+
+ if (node.updateOutputData) {
+ node.updateOutputData(link.origin_slot)
+ } else {
+ node.onExecute?.()
+ }
+
+ return link.data
+ }
+
+ /**
+ * Retrieves the input data type (in case this supports multiple input types)
+ * @param slot
+ * @returns datatype in string format
+ */
+ getInputDataType(slot: number): ISlotType | null {
+ if (!this.inputs) return null
+ if (slot >= this.inputs.length || this.inputs[slot].link == null)
+ return null
+ if (!this.graph) throw new NullGraphError()
+
+ const link_id = this.inputs[slot].link
+ const link = this.graph._links.get(link_id)
+ // bug: weird case but it happens sometimes
+ if (!link) return null
+
+ const node = this.graph.getNodeById(link.origin_id)
+ if (!node) return link.type
+
+ const output_info = node.outputs[link.origin_slot]
+ return output_info ? output_info.type : null
+ }
+
+ /**
+ * Retrieves the input data from one slot using its name instead of slot number
+ * @param slot_name
+ * @param force_update if set to true it will force the connected node of this slot to output data into this link
+ * @returns data or if it is not connected returns null
+ */
+ getInputDataByName(slot_name: string, force_update: boolean): unknown {
+ const slot = this.findInputSlot(slot_name)
+ return slot == -1 ? null : this.getInputData(slot, force_update)
+ }
+
+ /**
+ * tells you if there is a connection in one input slot
+ * @param slot The 0-based index of the input to check
+ * @returns `true` if the input slot has a link ID (does not perform validation)
+ */
+ isInputConnected(slot: number): boolean {
+ if (!this.inputs) return false
+ return slot < this.inputs.length && this.inputs[slot].link != null
+ }
+
+ /**
+ * tells you info about an input connection (which node, type, etc)
+ * @returns object or null { link: id, name: string, type: string or 0 }
+ */
+ getInputInfo(slot: number): INodeInputSlot | null {
+ return !this.inputs || !(slot < this.inputs.length)
+ ? null
+ : this.inputs[slot]
+ }
+
+ /**
+ * Returns the link info in the connection of an input slot
+ * @returns object or null
+ */
+ getInputLink(slot: number): LLink | null {
+ if (!this.inputs) return null
+
+ if (slot < this.inputs.length) {
+ if (!this.graph) throw new NullGraphError()
+
+ const input = this.inputs[slot]
+ if (input.link != null) {
+ return this.graph._links.get(input.link) ?? null
+ }
+ }
+ return null
+ }
+
+ /**
+ * returns the node connected in the input slot
+ * @returns node or null
+ */
+ getInputNode(slot: number): LGraphNode | null {
+ if (!this.inputs) return null
+ if (slot >= this.inputs.length) return null
+
+ const input = this.inputs[slot]
+ if (!input || input.link === null) return null
+ if (!this.graph) throw new NullGraphError()
+
+ const link_info = this.graph._links.get(input.link)
+ if (!link_info) return null
+
+ return this.graph.getNodeById(link_info.origin_id)
+ }
+
+ /**
+ * returns the value of an input with this name, otherwise checks if there is a property with that name
+ * @returns value
+ */
+ getInputOrProperty(name: string): unknown {
+ const { inputs } = this
+ if (!inputs?.length) {
+ return this.properties ? this.properties[name] : null
+ }
+ if (!this.graph) throw new NullGraphError()
+
+ for (const input of inputs) {
+ if (name == input.name && input.link != null) {
+ const link = this.graph._links.get(input.link)
+ if (link) return link.data
+ }
+ }
+ return this.properties[name]
+ }
+
+ /**
+ * tells you the last output data that went in that slot
+ * @returns object or null
+ */
+ getOutputData(slot: number): unknown {
+ if (!this.outputs) return null
+ if (slot >= this.outputs.length) return null
+
+ const info = this.outputs[slot]
+ return info._data
+ }
+
+ /**
+ * tells you info about an output connection (which node, type, etc)
+ * @returns object or null { name: string, type: string, links: [ ids of links in number ] }
+ */
+ getOutputInfo(slot: number): INodeOutputSlot | null {
+ return !this.outputs || !(slot < this.outputs.length)
+ ? null
+ : this.outputs[slot]
+ }
+
+ /**
+ * tells you if there is a connection in one output slot
+ */
+ isOutputConnected(slot: number): boolean {
+ if (!this.outputs) return false
+ return (
+ slot < this.outputs.length && Number(this.outputs[slot].links?.length) > 0
+ )
+ }
+
+ /**
+ * tells you if there is any connection in the output slots
+ */
+ isAnyOutputConnected(): boolean {
+ const { outputs } = this
+ if (!outputs) return false
+
+ for (const output of outputs) {
+ if (output.links?.length) return true
+ }
+ return false
+ }
+
+ /**
+ * retrieves all the nodes connected to this output slot
+ */
+ getOutputNodes(slot: number): LGraphNode[] | null {
+ const { outputs } = this
+ if (!outputs || outputs.length == 0) return null
+
+ if (slot >= outputs.length) return null
+
+ const { links } = outputs[slot]
+ if (!links || links.length == 0) return null
+ if (!this.graph) throw new NullGraphError()
+
+ const r: LGraphNode[] = []
+ for (const id of links) {
+ const link = this.graph._links.get(id)
+ if (link) {
+ const target_node = this.graph.getNodeById(link.target_id)
+ if (target_node) {
+ r.push(target_node)
+ }
+ }
+ }
+ return r
+ }
+
+ addOnTriggerInput(): number {
+ const trigS = this.findInputSlot('onTrigger')
+ if (trigS == -1) {
+ this.addInput('onTrigger', LiteGraph.EVENT, {
+ nameLocked: true
+ })
+ return this.findInputSlot('onTrigger')
+ }
+ return trigS
+ }
+
+ addOnExecutedOutput(): number {
+ const trigS = this.findOutputSlot('onExecuted')
+ if (trigS == -1) {
+ this.addOutput('onExecuted', LiteGraph.ACTION, {
+ nameLocked: true
+ })
+ return this.findOutputSlot('onExecuted')
+ }
+ return trigS
+ }
+
+ onAfterExecuteNode(param: unknown, options?: { action_call?: string }) {
+ const trigS = this.findOutputSlot('onExecuted')
+ if (trigS != -1) {
+ this.triggerSlot(trigS, param, null, options)
+ }
+ }
+
+ changeMode(modeTo: number): boolean {
+ switch (modeTo) {
+ case LGraphEventMode.ON_EVENT:
+ break
+
+ case LGraphEventMode.ON_TRIGGER:
+ this.addOnTriggerInput()
+ this.addOnExecutedOutput()
+ break
+
+ case LGraphEventMode.NEVER:
+ break
+
+ case LGraphEventMode.ALWAYS:
+ break
+
+ // @ts-expect-error Not impl.
+ case LiteGraph.ON_REQUEST:
+ break
+
+ default:
+ return false
+ break
+ }
+ this.mode = modeTo
+ return true
+ }
+
+ /**
+ * Triggers the node code execution, place a boolean/counter to mark the node as being executed
+ */
+ doExecute(param?: unknown, options?: { action_call?: string }): void {
+ options = options || {}
+ if (this.onExecute) {
+ // enable this to give the event an ID
+ options.action_call ||= `${this.id}_exec_${Math.floor(Math.random() * 9999)}`
+ if (!this.graph) throw new NullGraphError()
+
+ // @ts-expect-error Technically it works when id is a string. Array gets props.
+ this.graph.nodes_executing[this.id] = true
+ this.onExecute(param, options)
+ // @ts-expect-error deprecated
+ this.graph.nodes_executing[this.id] = false
+
+ // save execution/action ref
+ this.exec_version = this.graph.iteration
+ if (options?.action_call) {
+ this.action_call = options.action_call
+ // @ts-expect-error deprecated
+ this.graph.nodes_executedAction[this.id] = options.action_call
+ }
+ }
+ // the nFrames it will be used (-- each step), means "how old" is the event
+ this.execute_triggered = 2
+ this.onAfterExecuteNode?.(param, options)
+ }
+
+ /**
+ * Triggers an action, wrapped by logics to control execution flow
+ * @param action name
+ */
+ actionDo(
+ action: string,
+ param: unknown,
+ options: { action_call?: string }
+ ): void {
+ options = options || {}
+ if (this.onAction) {
+ // enable this to give the event an ID
+ options.action_call ||= `${this.id}_${action || 'action'}_${Math.floor(Math.random() * 9999)}`
+ if (!this.graph) throw new NullGraphError()
+
+ // @ts-expect-error deprecated
+ this.graph.nodes_actioning[this.id] = action || 'actioning'
+ this.onAction(action, param, options)
+ // @ts-expect-error deprecated
+ this.graph.nodes_actioning[this.id] = false
+
+ // save execution/action ref
+ if (options?.action_call) {
+ this.action_call = options.action_call
+ // @ts-expect-error deprecated
+ this.graph.nodes_executedAction[this.id] = options.action_call
+ }
+ }
+ // the nFrames it will be used (-- each step), means "how old" is the event
+ this.action_triggered = 2
+ this.onAfterExecuteNode?.(param, options)
+ }
+
+ /**
+ * Triggers an event in this node, this will trigger any output with the same name
+ * @param action name ( "on_play", ... ) if action is equivalent to false then the event is send to all
+ */
+ trigger(
+ action: string,
+ param: unknown,
+ options: { action_call?: string }
+ ): void {
+ const { outputs } = this
+ if (!outputs || !outputs.length) {
+ return
+ }
+
+ if (this.graph) this.graph._last_trigger_time = LiteGraph.getTime()
+
+ for (const [i, output] of outputs.entries()) {
+ if (
+ !output ||
+ output.type !== LiteGraph.EVENT ||
+ (action && output.name != action)
+ ) {
+ continue
+ }
+ this.triggerSlot(i, param, null, options)
+ }
+ }
+
+ /**
+ * Triggers a slot event in this node: cycle output slots and launch execute/action on connected nodes
+ * @param slot the index of the output slot
+ * @param link_id [optional] in case you want to trigger and specific output link in a slot
+ */
+ triggerSlot(
+ slot: number,
+ param: unknown,
+ link_id: number | null,
+ options?: { action_call?: string }
+ ): void {
+ options = options || {}
+ if (!this.outputs) return
+
+ if (slot == null) {
+ console.error('slot must be a number')
+ return
+ }
+
+ if (typeof slot !== 'number')
+ console.warn(
+ "slot must be a number, use node.trigger('name') if you want to use a string"
+ )
+
+ const output = this.outputs[slot]
+ if (!output) return
+
+ const links = output.links
+ if (!links || !links.length) return
+
+ if (!this.graph) throw new NullGraphError()
+ this.graph._last_trigger_time = LiteGraph.getTime()
+
+ // for every link attached here
+ for (const id of links) {
+ // to skip links
+ if (link_id != null && link_id != id) continue
+
+ const link_info = this.graph._links.get(id)
+ // not connected
+ if (!link_info) continue
+
+ link_info._last_time = LiteGraph.getTime()
+ const node = this.graph.getNodeById(link_info.target_id)
+ // node not found?
+ if (!node) continue
+
+ if (node.mode === LGraphEventMode.ON_TRIGGER) {
+ // generate unique trigger ID if not present
+ if (!options.action_call)
+ options.action_call = `${this.id}_trigg_${Math.floor(Math.random() * 9999)}`
+ // -- wrapping node.onExecute(param); --
+ node.doExecute?.(param, options)
+ } else if (node.onAction) {
+ // generate unique action ID if not present
+ if (!options.action_call)
+ options.action_call = `${this.id}_act_${Math.floor(Math.random() * 9999)}`
+ // pass the action name
+ const target_connection = node.inputs[link_info.target_slot]
+ node.actionDo(target_connection.name, param, options)
+ }
+ }
+ }
+
+ /**
+ * clears the trigger slot animation
+ * @param slot the index of the output slot
+ * @param link_id [optional] in case you want to trigger and specific output link in a slot
+ */
+ clearTriggeredSlot(slot: number, link_id: number): void {
+ if (!this.outputs) return
+
+ const output = this.outputs[slot]
+ if (!output) return
+
+ const links = output.links
+ if (!links || !links.length) return
+
+ if (!this.graph) throw new NullGraphError()
+
+ // for every link attached here
+ for (const id of links) {
+ // to skip links
+ if (link_id != null && link_id != id) continue
+
+ const link_info = this.graph._links.get(id)
+ // not connected
+ if (!link_info) continue
+
+ link_info._last_time = 0
+ }
+ }
+
+ /**
+ * changes node size and triggers callback
+ */
+ setSize(size: Size): void {
+ this.size = size
+ this.onResize?.(this.size)
+ }
+
+ /**
+ * Expands the node size to fit its content.
+ */
+ expandToFitContent(): void {
+ const newSize = this.computeSize()
+ this.setSize([
+ Math.max(this.size[0], newSize[0]),
+ Math.max(this.size[1], newSize[1])
+ ])
+ }
+
+ /**
+ * add a new property to this node
+ * @param type string defining the output type ("vec3","number",...)
+ * @param extra_info this can be used to have special properties of the property (like values, etc)
+ */
+ addProperty(
+ name: string,
+ default_value: NodeProperty | undefined,
+ type?: string,
+ extra_info?: Partial
+ ): INodePropertyInfo {
+ const o: INodePropertyInfo = { name, type, default_value }
+ if (extra_info) Object.assign(o, extra_info)
+
+ this.properties_info ||= []
+ this.properties_info.push(o)
+ this.properties ||= {}
+ this.properties[name] = default_value
+ return o
+ }
+
+ /**
+ * add a new output slot to use in this node
+ * @param type string defining the output type ("vec3","number",...)
+ * @param extra_info this can be used to have special properties of an output (label, special color, position, etc)
+ */
+ addOutput>(
+ name: string,
+ type: ISlotType,
+ extra_info?: TProperties
+ ): INodeOutputSlot & TProperties {
+ const output = Object.assign(
+ new NodeOutputSlot({ name, type, links: null }, this),
+ extra_info
+ )
+
+ this.outputs ||= []
+ this.outputs.push(output)
+ this.onOutputAdded?.(output)
+
+ if (LiteGraph.auto_load_slot_types)
+ LiteGraph.registerNodeAndSlotType(this, type, true)
+
+ this.expandToFitContent()
+ this.setDirtyCanvas(true, true)
+ return output
+ }
+
+ /**
+ * remove an existing output slot
+ */
+ removeOutput(slot: number): void {
+ // Only disconnect if node is part of a graph
+ if (this.graph) {
+ this.disconnectOutput(slot)
+ }
+ const { outputs } = this
+ outputs.splice(slot, 1)
+
+ for (let i = slot; i < outputs.length; ++i) {
+ const output = outputs[i]
+ if (!output || !output.links) continue
+
+ // Only update link indices if node is part of a graph
+ if (this.graph) {
+ for (const linkId of output.links) {
+ const link = this.graph._links.get(linkId)
+ if (link) link.origin_slot--
+ }
+ }
+ }
+
+ this.onOutputRemoved?.(slot)
+ this.setDirtyCanvas(true, true)
+ }
+
+ /**
+ * add a new input slot to use in this node
+ * @param type string defining the input type ("vec3","number",...), it its a generic one use 0
+ * @param extra_info this can be used to have special properties of an input (label, color, position, etc)
+ */
+ addInput>(
+ name: string,
+ type: ISlotType,
+ extra_info?: TProperties
+ ): INodeInputSlot & TProperties {
+ type ||= 0
+
+ const input = Object.assign(
+ new NodeInputSlot({ name, type, link: null }, this),
+ extra_info
+ )
+
+ this.inputs ||= []
+ this.inputs.push(input)
+ this.expandToFitContent()
+
+ this.onInputAdded?.(input)
+ LiteGraph.registerNodeAndSlotType(this, type)
+
+ this.setDirtyCanvas(true, true)
+ return input
+ }
+
+ /**
+ * remove an existing input slot
+ */
+ removeInput(slot: number): void {
+ // Only disconnect if node is part of a graph
+ if (this.graph) {
+ this.disconnectInput(slot, true)
+ }
+ const { inputs } = this
+ const slot_info = inputs.splice(slot, 1)
+
+ for (let i = slot; i < inputs.length; ++i) {
+ const input = inputs[i]
+ if (!input?.link) continue
+
+ // Only update link indices if node is part of a graph
+ if (this.graph) {
+ const link = this.graph._links.get(input.link)
+ if (link) link.target_slot--
+ }
+ }
+ this.onInputRemoved?.(slot, slot_info[0])
+ this.setDirtyCanvas(true, true)
+ }
+
+ /**
+ * computes the minimum size of a node according to its inputs and output slots
+ * @returns the total size
+ */
+ computeSize(out?: Size): Size {
+ const ctorSize = this.constructor.size
+ if (ctorSize) return [ctorSize[0], ctorSize[1]]
+
+ const { inputs, outputs, widgets } = this
+ let rows = Math.max(
+ inputs ? inputs.filter((input) => !isWidgetInputSlot(input)).length : 1,
+ outputs ? outputs.length : 1
+ )
+ const size = out ?? [0, 0]
+ rows = Math.max(rows, 1)
+ // although it should be graphcanvas.inner_text_font size
+ const font_size = LiteGraph.NODE_TEXT_SIZE
+
+ const padLeft = LiteGraph.NODE_TITLE_HEIGHT
+ const padRight = padLeft * 0.33
+ const title_width =
+ padLeft + compute_text_size(this.title, this.titleFontStyle) + padRight
+ let input_width = 0
+ let widgetWidth = 0
+ let output_width = 0
+
+ if (inputs) {
+ for (const input of inputs) {
+ const text = input.label || input.localized_name || input.name || ''
+ const text_width = compute_text_size(text, this.innerFontStyle)
+ if (isWidgetInputSlot(input)) {
+ const widget = this.getWidgetFromSlot(input)
+ if (widget && !this.isWidgetVisible(widget)) continue
+
+ if (text_width > widgetWidth) widgetWidth = text_width
+ } else {
+ if (text_width > input_width) input_width = text_width
+ }
+ }
+ }
+
+ if (outputs) {
+ for (const output of outputs) {
+ const text = output.label || output.localized_name || output.name || ''
+ const text_width = compute_text_size(text, this.innerFontStyle)
+ if (output_width < text_width) output_width = text_width
+ }
+ }
+
+ const minWidth = LiteGraph.NODE_WIDTH * (widgets?.length ? 1.5 : 1)
+ // Text + slot width + centre padding
+ const centrePadding = input_width && output_width ? 5 : 0
+ const slotsWidth =
+ input_width +
+ output_width +
+ 2 * LiteGraph.NODE_SLOT_HEIGHT +
+ centrePadding
+
+ // Total distance from edge of node to the inner edge of the widget 'previous' arrow button
+ const widgetMargin =
+ BaseWidget.margin + BaseWidget.arrowMargin + BaseWidget.arrowWidth
+ const widgetPadding = BaseWidget.minValueWidth + 2 * widgetMargin
+ if (widgetWidth) widgetWidth += widgetPadding
+
+ size[0] = Math.max(slotsWidth, widgetWidth, title_width, minWidth)
+ size[1] =
+ (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT
+
+ // Get widget height & expand size if necessary
+ let widgets_height = 0
+ if (widgets?.length) {
+ for (const widget of widgets) {
+ if (!this.isWidgetVisible(widget)) continue
+
+ let widget_height = 0
+ if (widget.computeSize) {
+ widget_height += widget.computeSize(size[0])[1]
+ } else if (widget.computeLayoutSize) {
+ // Expand widget width if necessary
+ const { minHeight, minWidth } = widget.computeLayoutSize(this)
+ const widgetWidth = minWidth + widgetPadding
+ if (widgetWidth > size[0]) size[0] = widgetWidth
+
+ widget_height += minHeight
+ } else {
+ widget_height += LiteGraph.NODE_WIDGET_HEIGHT
+ }
+ widgets_height += widget_height + 4
+ }
+ widgets_height += 8
+ }
+
+ // compute height using widgets height
+ if (this.widgets_up) size[1] = Math.max(size[1], widgets_height)
+ else if (this.widgets_start_y != null)
+ size[1] = Math.max(size[1], widgets_height + this.widgets_start_y)
+ else size[1] += widgets_height
+
+ function compute_text_size(text: string, fontStyle: string) {
+ return (
+ LGraphCanvas._measureText?.(text, fontStyle) ??
+ font_size * (text?.length ?? 0) * 0.6
+ )
+ }
+
+ if (this.constructor.min_height && size[1] < this.constructor.min_height) {
+ size[1] = this.constructor.min_height
+ }
+
+ // margin
+ size[1] += 6
+
+ return size
+ }
+
+ inResizeCorner(canvasX: number, canvasY: number): boolean {
+ const rows = this.outputs ? this.outputs.length : 1
+ const outputs_offset =
+ (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT
+ return isInRectangle(
+ canvasX,
+ canvasY,
+ this.pos[0] + this.size[0] - 15,
+ this.pos[1] + Math.max(this.size[1] - 15, outputs_offset),
+ 20,
+ 20
+ )
+ }
+
+ /**
+ * Returns which resize corner the point is over, if any.
+ * @param canvasX X position in canvas coordinates
+ * @param canvasY Y position in canvas coordinates
+ * @returns The compass corner the point is in, otherwise `undefined`.
+ */
+ findResizeDirection(
+ canvasX: number,
+ canvasY: number
+ ): CompassCorners | undefined {
+ if (this.resizable === false) return
+
+ const { boundingRect } = this
+ if (!boundingRect.containsXy(canvasX, canvasY)) return
+
+ // Check corners first (they take priority over edges)
+ return boundingRect.findContainingCorner(
+ canvasX,
+ canvasY,
+ LGraphNode.resizeHandleSize
+ )
+ }
+
+ /**
+ * returns all the info available about a property of this node.
+ * @param property name of the property
+ * @returns the object with all the available info
+ */
+ getPropertyInfo(property: string) {
+ let info = null
+
+ // there are several ways to define info about a property
+ // legacy mode
+ const { properties_info } = this
+ if (properties_info) {
+ for (const propInfo of properties_info) {
+ if (propInfo.name == property) {
+ info = propInfo
+ break
+ }
+ }
+ }
+ // litescene mode using the constructor
+ // @ts-expect-error deprecated https://github.com/Comfy-Org/litegraph.js/issues/639
+ if (this.constructor[`@${property}`])
+ // @ts-expect-error deprecated https://github.com/Comfy-Org/litegraph.js/issues/639
+ info = this.constructor[`@${property}`]
+
+ if (this.constructor.widgets_info?.[property])
+ info = this.constructor.widgets_info[property]
+
+ // litescene mode using the constructor
+ if (!info && this.onGetPropertyInfo) {
+ info = this.onGetPropertyInfo(property)
+ }
+
+ info ||= {}
+ info.type ||= typeof this.properties[property]
+ if (info.widget == 'combo') info.type = 'enum'
+
+ return info
+ }
+
+ /**
+ * Defines a widget inside the node, it will be rendered on top of the node, you can control lots of properties
+ * @param type the widget type
+ * @param name the text to show on the widget
+ * @param value the default value
+ * @param callback function to call when it changes (optionally, it can be the name of the property to modify)
+ * @param options the object that contains special properties of this widget
+ * @returns the created widget object
+ */
+ addWidget<
+ Type extends TWidgetType,
+ TValue extends WidgetTypeMap[Type]['value']
+ >(
+ type: Type,
+ name: string,
+ value: TValue,
+ callback: IBaseWidget['callback'] | string | null,
+ options?: IWidgetOptions | string
+ ): WidgetTypeMap[Type] | IBaseWidget {
+ this.widgets ||= []
+
+ if (!options && callback && typeof callback === 'object') {
+ options = callback
+ callback = null
+ }
+
+ // options can be the property name
+ options ||= {}
+ if (typeof options === 'string') options = { property: options }
+
+ // callback can be the property name
+ if (callback && typeof callback === 'string') {
+ options.property = callback
+ callback = null
+ }
+
+ const w: IBaseWidget & { type: Type } = {
+ // @ts-expect-error - Type casting for widget type property
+ type: type.toLowerCase(),
+ name: name,
+ value: value,
+ callback: typeof callback !== 'function' ? undefined : callback,
+ options,
+ y: 0
+ }
+
+ if (w.options.y !== undefined) {
+ w.y = w.options.y
+ }
+
+ if (!callback && !w.options.callback && !w.options.property) {
+ console.warn(
+ 'LiteGraph addWidget(...) without a callback or property assigned'
+ )
+ }
+ if (type == 'combo' && !w.options.values) {
+ throw "LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }"
+ }
+
+ const widget = this.addCustomWidget(w)
+ this.expandToFitContent()
+ return widget
+ }
+
+ addCustomWidget(
+ custom_widget: TPlainWidget
+ ): TPlainWidget | WidgetTypeMap[TPlainWidget['type']] {
+ this.widgets ||= []
+ const widget = toConcreteWidget(custom_widget, this, false) ?? custom_widget
+ this.widgets.push(widget)
+ return widget
+ }
+
+ addTitleButton(options: LGraphButtonOptions): LGraphButton {
+ this.title_buttons ||= []
+ const button = new LGraphButton(options)
+ this.title_buttons.push(button)
+ return button
+ }
+
+ onTitleButtonClick(button: LGraphButton, canvas: LGraphCanvas): void {
+ // Dispatch event for button click
+ canvas.dispatch('litegraph:node-title-button-clicked', {
+ node: this,
+ button: button
+ })
+ }
+
+ removeWidgetByName(name: string): void {
+ const widget = this.widgets?.find((x) => x.name === name)
+ if (widget) this.removeWidget(widget)
+ }
+
+ removeWidget(widget: IBaseWidget): void {
+ if (!this.widgets)
+ throw new Error('removeWidget called on node without widgets')
+
+ const widgetIndex = this.widgets.indexOf(widget)
+ if (widgetIndex === -1) throw new Error('Widget not found on this node')
+
+ // Clean up slot references to prevent memory leaks
+ if (this.inputs) {
+ for (const input of this.inputs) {
+ if (input._widget === widget) {
+ input._widget = undefined
+ input.widget = undefined
+ }
+ }
+ }
+
+ widget.onRemove?.()
+ this.widgets.splice(widgetIndex, 1)
+ }
+
+ ensureWidgetRemoved(widget: IBaseWidget): void {
+ try {
+ this.removeWidget(widget)
+ } catch (error) {
+ console.error('Failed to remove widget', error)
+ }
+ }
+
+ move(deltaX: number, deltaY: number): void {
+ if (this.pinned) return
+
+ // If Vue nodes mode is enabled, skip LiteGraph's direct position update
+ // The layout store will handle the movement and sync back to LiteGraph
+ if (LiteGraph.vueNodesMode) {
+ // Vue nodes handle their own dragging through the layout store
+ // This prevents the snap-back issue from conflicting position updates
+ return
+ }
+
+ this.pos[0] += deltaX
+ this.pos[1] += deltaY
+ }
+
+ /**
+ * Internal method to measure the node for rendering. Prefer {@link boundingRect} where possible.
+ *
+ * Populates {@link out} with the results in graph space.
+ * Populates {@link _collapsed_width} with the collapsed width if the node is collapsed.
+ * Adjusts for title and collapsed status, but does not call {@link onBounding}.
+ * @param out `x, y, width, height` are written to this array.
+ * @param ctx The canvas context to use for measuring text.
+ */
+ measure(out: Rect, ctx?: CanvasRenderingContext2D): void {
+ const titleMode = this.title_mode
+ const renderTitle =
+ titleMode != TitleMode.TRANSPARENT_TITLE &&
+ titleMode != TitleMode.NO_TITLE
+ const titleHeight = renderTitle ? LiteGraph.NODE_TITLE_HEIGHT : 0
+
+ out[0] = this.pos[0]
+ out[1] = this.pos[1] + -titleHeight
+ if (!this.flags?.collapsed) {
+ out[2] = this.size[0]
+ out[3] = this.size[1] + titleHeight
+ } else {
+ if (ctx) ctx.font = this.innerFontStyle
+ this._collapsed_width = Math.min(
+ this.size[0],
+ ctx
+ ? ctx.measureText(this.getTitle() ?? '').width +
+ LiteGraph.NODE_TITLE_HEIGHT * 2
+ : 0
+ )
+ out[2] = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH
+ out[3] = LiteGraph.NODE_TITLE_HEIGHT
+ }
+ }
+
+ /**
+ * returns the bounding of the object, used for rendering purposes
+ * @param out {Rect?} [optional] a place to store the output, to free garbage
+ * @param includeExternal {boolean?} [optional] set to true to
+ * include the shadow and connection points in the bounding calculation
+ * @returns the bounding box in format of [topleft_cornerx, topleft_cornery, width, height]
+ */
+ getBounding(out?: Rect, includeExternal?: boolean): Rect {
+ out ||= [0, 0, 0, 0]
+
+ const rect = includeExternal ? this.renderArea : this.boundingRect
+ out[0] = rect[0]
+ out[1] = rect[1]
+ out[2] = rect[2]
+ out[3] = rect[3]
+
+ return out
+ }
+
+ /**
+ * Calculates the render area of this node, populating both {@link boundingRect} and {@link renderArea}.
+ * Called automatically at the start of every frame.
+ */
+ updateArea(ctx?: CanvasRenderingContext2D): void {
+ const bounds = this.#boundingRect
+ this.measure(bounds, ctx)
+ this.onBounding?.(bounds)
+
+ const renderArea = this.#renderArea
+ renderArea.set(bounds)
+ // 4 offset for collapsed node connection points
+ renderArea[0] -= 4
+ renderArea[1] -= 4
+ // Add shadow & left offset
+ renderArea[2] += 6 + 4
+ // Add shadow & top offsets
+ renderArea[3] += 5 + 4
+ }
+
+ /**
+ * checks if a point is inside the shape of a node
+ */
+ isPointInside(x: number, y: number): boolean {
+ return isInRect(x, y, this.boundingRect)
+ }
+
+ /**
+ * Checks if the provided point is inside this node's collapse button area.
+ * @param x X co-ordinate to check
+ * @param y Y co-ordinate to check
+ * @returns true if the x,y point is in the collapse button area, otherwise false
+ */
+ isPointInCollapse(x: number, y: number): boolean {
+ const squareLength = LiteGraph.NODE_TITLE_HEIGHT
+ return isInRectangle(
+ x,
+ y,
+ this.pos[0],
+ this.pos[1] - squareLength,
+ squareLength,
+ squareLength
+ )
+ }
+
+ /**
+ * Returns the input slot at the given position. Uses full 20 height, and approximates the label length.
+ * @param pos The graph co-ordinates to check
+ * @returns The input slot at the given position if found, otherwise `undefined`.
+ */
+ getInputOnPos(pos: Point): INodeInputSlot | undefined {
+ return getNodeInputOnPos(this, pos[0], pos[1])?.input
+ }
+
+ /**
+ * Returns the output slot at the given position. Uses full 20x20 box for the slot.
+ * @param pos The graph co-ordinates to check
+ * @returns The output slot at the given position if found, otherwise `undefined`.
+ */
+ getOutputOnPos(pos: Point): INodeOutputSlot | undefined {
+ return getNodeOutputOnPos(this, pos[0], pos[1])?.output
+ }
+
+ /**
+ * Returns the input or output slot at the given position.
+ *
+ * Tries {@link getNodeInputOnPos} first, then {@link getNodeOutputOnPos}.
+ * @param pos The graph co-ordinates to check
+ * @returns The input or output slot at the given position if found, otherwise `undefined`.
+ */
+ getSlotOnPos(pos: Point): INodeInputSlot | INodeOutputSlot | undefined {
+ if (!isPointInRect(pos, this.boundingRect)) return
+
+ return this.getInputOnPos(pos) ?? this.getOutputOnPos(pos)
+ }
+
+ /**
+ * @deprecated Use {@link getSlotOnPos} instead.
+ * checks if a point is inside a node slot, and returns info about which slot
+ * @param x
+ * @param y
+ * @returns if found the object contains { input|output: slot object, slot: number, link_pos: [x,y] }
+ */
+ getSlotInPosition(x: number, y: number): IFoundSlot | null {
+ // search for inputs
+ const { inputs, outputs } = this
+
+ if (inputs) {
+ for (const [i, input] of inputs.entries()) {
+ const pos = this.getInputPos(i)
+ if (isInRectangle(x, y, pos[0] - 10, pos[1] - 10, 20, 20)) {
+ return { input, slot: i, link_pos: pos }
+ }
+ }
+ }
+
+ if (outputs) {
+ for (const [i, output] of outputs.entries()) {
+ const pos = this.getOutputPos(i)
+ if (isInRectangle(x, y, pos[0] - 10, pos[1] - 10, 20, 20)) {
+ return { output, slot: i, link_pos: pos }
+ }
+ }
+ }
+
+ return null
+ }
+
+ /**
+ * Gets the widget on this node at the given co-ordinates.
+ * @param canvasX X co-ordinate in graph space
+ * @param canvasY Y co-ordinate in graph space
+ * @returns The widget found, otherwise `null`
+ */
+ getWidgetOnPos(
+ canvasX: number,
+ canvasY: number,
+ includeDisabled = false
+ ): IBaseWidget | undefined {
+ const { widgets, pos, size } = this
+ if (!widgets?.length) return
+
+ const x = canvasX - pos[0]
+ const y = canvasY - pos[1]
+ const nodeWidth = size[0]
+
+ for (const widget of widgets) {
+ if (
+ (widget.computedDisabled && !includeDisabled) ||
+ !this.isWidgetVisible(widget)
+ ) {
+ continue
+ }
+
+ const h =
+ widget.computedHeight ??
+ widget.computeSize?.(nodeWidth)[1] ??
+ LiteGraph.NODE_WIDGET_HEIGHT
+
+ const maybeDOMWidget = widget as { margin?: number }
+ const mtop = maybeDOMWidget.margin ?? -2
+ const mbot = maybeDOMWidget.margin ?? 2
+ const mx = maybeDOMWidget.margin ?? 6
+
+ const w = widget.width || nodeWidth
+ if (
+ widget.last_y !== undefined &&
+ isInRectangle(
+ x,
+ y,
+ mx,
+ widget.last_y + mtop,
+ w - 2 * mx,
+ h - mtop - mbot
+ )
+ ) {
+ return widget
+ }
+ }
+ }
+
+ /**
+ * Returns the input slot with a given name (used for dynamic slots), -1 if not found
+ * @param name the name of the slot to find
+ * @param returnObj if the obj itself wanted
+ * @returns the slot (-1 if not found)
+ */
+ findInputSlot(
+ name: string,
+ returnObj?: TReturn
+ ): number
+ findInputSlot(
+ name: string,
+ returnObj?: TReturn
+ ): INodeInputSlot
+ findInputSlot(name: string, returnObj: boolean = false) {
+ const { inputs } = this
+ if (!inputs) return -1
+
+ for (const [i, input] of inputs.entries()) {
+ if (name == input.name) {
+ return !returnObj ? i : input
+ }
+ }
+ return -1
+ }
+
+ /**
+ * returns the output slot with a given name (used for dynamic slots), -1 if not found
+ * @param name the name of the slot to find
+ * @param returnObj if the obj itself wanted
+ * @returns the slot (-1 if not found)
+ */
+ findOutputSlot(
+ name: string,
+ returnObj?: TReturn
+ ): number
+ findOutputSlot(
+ name: string,
+ returnObj?: TReturn
+ ): INodeOutputSlot
+ findOutputSlot(name: string, returnObj: boolean = false) {
+ const { outputs } = this
+ if (!outputs) return -1
+
+ for (const [i, output] of outputs.entries()) {
+ if (name == output.name) {
+ return !returnObj ? i : output
+ }
+ }
+ return -1
+ }
+
+ /**
+ * Finds the first free input slot.
+ * @param optsIn
+ * @returns The index of the first matching slot, the slot itself if returnObj is true, or -1 if not found.
+ */
+ findInputSlotFree(
+ optsIn?: FindFreeSlotOptions & { returnObj?: TReturn }
+ ): number
+ findInputSlotFree(
+ optsIn?: FindFreeSlotOptions & { returnObj?: TReturn }
+ ): INodeInputSlot | -1
+ findInputSlotFree(optsIn?: FindFreeSlotOptions) {
+ return this.#findFreeSlot(this.inputs, optsIn)
+ }
+
+ /**
+ * Finds the first free output slot.
+ * @param optsIn
+ * @returns The index of the first matching slot, the slot itself if returnObj is true, or -1 if not found.
+ */
+ findOutputSlotFree(
+ optsIn?: FindFreeSlotOptions & { returnObj?: TReturn }
+ ): number
+ findOutputSlotFree(
+ optsIn?: FindFreeSlotOptions & { returnObj?: TReturn }
+ ): INodeOutputSlot | -1
+ findOutputSlotFree(optsIn?: FindFreeSlotOptions) {
+ return this.#findFreeSlot(this.outputs, optsIn)
+ }
+
+ /**
+ * Finds the next free slot
+ * @param slots The slots to search, i.e. this.inputs or this.outputs
+ */
+ #findFreeSlot(
+ slots: TSlot[],
+ options?: FindFreeSlotOptions
+ ): TSlot | number {
+ const defaults = {
+ returnObj: false,
+ typesNotAccepted: []
+ }
+ const opts = Object.assign(defaults, options || {})
+ const length = slots?.length
+ if (!(length > 0)) return -1
+
+ for (let i = 0; i < length; ++i) {
+ const slot: TSlot & IGenericLinkOrLinks = slots[i]
+ if (!slot || slot.link || slot.links?.length) continue
+ if (opts.typesNotAccepted?.includes?.(slot.type)) continue
+ return !opts.returnObj ? i : slot
+ }
+ return -1
+ }
+
+ /**
+ * findSlotByType for INPUTS
+ */
+ findInputSlotByType(
+ type: ISlotType,
+ returnObj?: TReturn,
+ preferFreeSlot?: boolean,
+ doNotUseOccupied?: boolean
+ ): number
+ findInputSlotByType(
+ type: ISlotType,
+ returnObj?: TReturn,
+ preferFreeSlot?: boolean,
+ doNotUseOccupied?: boolean
+ ): INodeInputSlot
+ findInputSlotByType(
+ type: ISlotType,
+ returnObj?: boolean,
+ preferFreeSlot?: boolean,
+ doNotUseOccupied?: boolean
+ ) {
+ return this.#findSlotByType(
+ this.inputs,
+ type,
+ returnObj,
+ preferFreeSlot,
+ doNotUseOccupied
+ )
+ }
+
+ /**
+ * findSlotByType for OUTPUTS
+ */
+ findOutputSlotByType(
+ type: ISlotType,
+ returnObj?: TReturn,
+ preferFreeSlot?: boolean,
+ doNotUseOccupied?: boolean
+ ): number
+ findOutputSlotByType(
+ type: ISlotType,
+ returnObj?: TReturn,
+ preferFreeSlot?: boolean,
+ doNotUseOccupied?: boolean
+ ): INodeOutputSlot
+ findOutputSlotByType(
+ type: ISlotType,
+ returnObj?: boolean,
+ preferFreeSlot?: boolean,
+ doNotUseOccupied?: boolean
+ ) {
+ return this.#findSlotByType(
+ this.outputs,
+ type,
+ returnObj,
+ preferFreeSlot,
+ doNotUseOccupied
+ )
+ }
+
+ /**
+ * returns the output (or input) slot with a given type, -1 if not found
+ * @param input use inputs instead of outputs
+ * @param type the type of the slot to find
+ * @param returnObj if the obj itself wanted
+ * @param preferFreeSlot if we want a free slot (if not found, will return the first of the type anyway)
+ * @returns the slot (-1 if not found)
+ */
+ findSlotByType(
+ input: TSlot,
+ type: ISlotType,
+ returnObj?: TReturn,
+ preferFreeSlot?: boolean,
+ doNotUseOccupied?: boolean
+ ): number
+ findSlotByType(
+ input: TSlot,
+ type: ISlotType,
+ returnObj?: TReturn,
+ preferFreeSlot?: boolean,
+ doNotUseOccupied?: boolean
+ ): INodeInputSlot | -1
+ findSlotByType(
+ input: TSlot,
+ type: ISlotType,
+ returnObj?: TReturn,
+ preferFreeSlot?: boolean,
+ doNotUseOccupied?: boolean
+ ): INodeOutputSlot | -1
+ findSlotByType(
+ input: boolean,
+ type: ISlotType,
+ returnObj?: boolean,
+ preferFreeSlot?: boolean,
+ doNotUseOccupied?: boolean
+ ): number | INodeOutputSlot | INodeInputSlot {
+ return input
+ ? this.#findSlotByType(
+ this.inputs,
+ type,
+ returnObj,
+ preferFreeSlot,
+ doNotUseOccupied
+ )
+ : this.#findSlotByType(
+ this.outputs,
+ type,
+ returnObj,
+ preferFreeSlot,
+ doNotUseOccupied
+ )
+ }
+
+ /**
+ * Finds a matching slot from those provided, returning the slot itself or its index in {@link slots}.
+ * @param slots Slots to search (this.inputs or this.outputs)
+ * @param type Type of slot to look for
+ * @param returnObj If true, returns the slot itself. Otherwise, the index.
+ * @param preferFreeSlot Prefer a free slot, but if none are found, fall back to an occupied slot.
+ * @param doNotUseOccupied Do not fall back to occupied slots.
+ * @see {findSlotByType}
+ * @see {findOutputSlotByType}
+ * @see {findInputSlotByType}
+ * @returns If a match is found, the slot if returnObj is true, otherwise the index. If no matches are found, -1
+ */
+ #findSlotByType(
+ slots: TSlot[],
+ type: ISlotType,
+ returnObj?: boolean,
+ preferFreeSlot?: boolean,
+ doNotUseOccupied?: boolean
+ ): TSlot | number {
+ const length = slots?.length
+ if (!length) return -1
+
+ // Empty string and * match anything (type: 0)
+ if (type == '' || type == '*') type = 0
+ const sourceTypes = String(type).toLowerCase().split(',')
+
+ // Run the search
+ let occupiedSlot: number | TSlot | null = null
+ for (let i = 0; i < length; ++i) {
+ const slot: TSlot & IGenericLinkOrLinks = slots[i]
+ const destTypes =
+ slot.type == '0' || slot.type == '*'
+ ? ['0']
+ : String(slot.type).toLowerCase().split(',')
+
+ for (const sourceType of sourceTypes) {
+ // TODO: Remove _event_ entirely.
+ const source = sourceType == '_event_' ? LiteGraph.EVENT : sourceType
+
+ for (const destType of destTypes) {
+ const dest = destType == '_event_' ? LiteGraph.EVENT : destType
+
+ if (source == dest || source === '*' || dest === '*') {
+ if (preferFreeSlot && (slot.links?.length || slot.link != null)) {
+ // In case we can't find a free slot.
+ occupiedSlot ??= returnObj ? slot : i
+ continue
+ }
+ return returnObj ? slot : i
+ }
+ }
+ }
+ }
+
+ return doNotUseOccupied ? -1 : (occupiedSlot ?? -1)
+ }
+
+ /**
+ * Determines the slot index to connect to when attempting to connect by type.
+ * @param findInputs If true, searches for an input. Otherwise, an output.
+ * @param node The node at the other end of the connection.
+ * @param slotType The type of slot at the other end of the connection.
+ * @param options Search restrictions to adhere to.
+ * @see {connectByType}
+ * @see {connectByTypeOutput}
+ */
+ findConnectByTypeSlot(
+ findInputs: boolean,
+ node: LGraphNode,
+ slotType: ISlotType,
+ options?: ConnectByTypeOptions
+ ): number | undefined {
+ // LEGACY: Old options names
+ if (options && typeof options === 'object') {
+ if ('firstFreeIfInputGeneralInCase' in options)
+ options.wildcardToTyped = !!options.firstFreeIfInputGeneralInCase
+ if ('firstFreeIfOutputGeneralInCase' in options)
+ options.wildcardToTyped = !!options.firstFreeIfOutputGeneralInCase
+ if ('generalTypeInCase' in options)
+ options.typedToWildcard = !!options.generalTypeInCase
+ }
+ const optsDef: ConnectByTypeOptions = {
+ createEventInCase: true,
+ wildcardToTyped: true,
+ typedToWildcard: true
+ }
+ const opts = Object.assign(optsDef, options)
+
+ if (!this.graph) throw new NullGraphError()
+
+ if (node && typeof node === 'number') {
+ const nodeById = this.graph.getNodeById(node)
+ if (!nodeById) return
+
+ node = nodeById
+ }
+ const slot = node.findSlotByType(findInputs, slotType, false, true)
+ if (slot >= 0 && slot !== null) return slot
+
+ // TODO: Remove or reimpl. events. WILL CREATE THE onTrigger IN SLOT
+ if (opts.createEventInCase && slotType == LiteGraph.EVENT) {
+ if (findInputs) return -1
+ if (LiteGraph.do_add_triggers_slots) return node.addOnExecutedOutput()
+ }
+
+ // connect to the first general output slot if not found a specific type and
+ if (opts.typedToWildcard) {
+ const generalSlot = node.findSlotByType(findInputs, 0, false, true, true)
+ if (generalSlot >= 0) return generalSlot
+ }
+ // connect to the first free input slot if not found a specific type and this output is general
+ if (
+ opts.wildcardToTyped &&
+ (slotType == 0 || slotType == '*' || slotType == '')
+ ) {
+ const opt = { typesNotAccepted: [LiteGraph.EVENT] }
+ const nonEventSlot = findInputs
+ ? node.findInputSlotFree(opt)
+ : node.findOutputSlotFree(opt)
+ if (nonEventSlot >= 0) return nonEventSlot
+ }
+ }
+
+ /**
+ * Finds the first free output slot with any of the comma-delimited types in {@link type}.
+ *
+ * If no slots are free, falls back in order to:
+ * - The first free wildcard slot
+ * - The first occupied slot
+ * - The first occupied wildcard slot
+ * @param type The {@link ISlotType type} of slot to find
+ * @returns The index and slot if found, otherwise `undefined`.
+ */
+ findOutputByType(
+ type: ISlotType
+ ): { index: number; slot: INodeOutputSlot } | undefined {
+ return findFreeSlotOfType(
+ this.outputs,
+ type,
+ (output) => !output.links?.length
+ )
+ }
+
+ /**
+ * Finds the first free input slot with any of the comma-delimited types in {@link type}.
+ *
+ * If no slots are free, falls back in order to:
+ * - The first free wildcard slot
+ * - The first occupied slot
+ * - The first occupied wildcard slot
+ * @param type The {@link ISlotType type} of slot to find
+ * @returns The index and slot if found, otherwise `undefined`.
+ */
+ findInputByType(
+ type: ISlotType
+ ): { index: number; slot: INodeInputSlot } | undefined {
+ return findFreeSlotOfType(
+ this.inputs,
+ type,
+ (input) =>
+ input.link == null || !!this.graph?.getLink(input.link)?._dragging
+ )
+ }
+
+ /**
+ * connect this node output to the input of another node BY TYPE
+ * @param slot (could be the number of the slot or the string with the name of the slot)
+ * @param target_node the target node
+ * @param target_slotType the input slot type of the target node
+ * @returns the link_info is created, otherwise null
+ */
+ connectByType(
+ slot: number | string,
+ target_node: LGraphNode,
+ target_slotType: ISlotType,
+ optsIn?: ConnectByTypeOptions
+ ): LLink | null {
+ const slotIndex = this.findConnectByTypeSlot(
+ true,
+ target_node,
+ target_slotType,
+ optsIn
+ )
+ if (slotIndex !== undefined)
+ return this.connect(slot, target_node, slotIndex, optsIn?.afterRerouteId)
+
+ // No compatible slot found - connection not possible
+ return null
+ }
+
+ /**
+ * connect this node input to the output of another node BY TYPE
+ * @param slot (could be the number of the slot or the string with the name of the slot)
+ * @param source_node the target node
+ * @param source_slotType the output slot type of the target node
+ * @returns the link_info is created, otherwise null
+ */
+ connectByTypeOutput(
+ slot: number | string,
+ source_node: LGraphNode,
+ source_slotType: ISlotType,
+ optsIn?: ConnectByTypeOptions
+ ): LLink | null {
+ // LEGACY: Old options names
+ if (typeof optsIn === 'object') {
+ if ('firstFreeIfInputGeneralInCase' in optsIn)
+ optsIn.wildcardToTyped = !!optsIn.firstFreeIfInputGeneralInCase
+ if ('generalTypeInCase' in optsIn)
+ optsIn.typedToWildcard = !!optsIn.generalTypeInCase
+ }
+ const slotIndex = this.findConnectByTypeSlot(
+ false,
+ source_node,
+ source_slotType,
+ optsIn
+ )
+ if (slotIndex !== undefined)
+ return source_node.connect(slotIndex, this, slot, optsIn?.afterRerouteId)
+
+ console.error(
+ '[connectByType]: no way to connect type:',
+ source_slotType,
+ 'to node:',
+ source_node
+ )
+ return null
+ }
+
+ canConnectTo(
+ node: NodeLike,
+ toSlot: INodeInputSlot | SubgraphIO,
+ fromSlot: INodeOutputSlot | SubgraphIO
+ ) {
+ return (
+ this.id !== node.id &&
+ LiteGraph.isValidConnection(fromSlot.type, toSlot.type)
+ )
+ }
+
+ /**
+ * Connect an output of this node to an input of another node
+ * @param slot (could be the number of the slot or the string with the name of the slot)
+ * @param target_node the target node
+ * @param target_slot the input slot of the target node (could be the number of the slot or the string with the name of the slot, or -1 to connect a trigger)
+ * @returns the link_info is created, otherwise null
+ */
+ connect(
+ slot: number | string,
+ target_node: LGraphNode,
+ target_slot: ISlotType,
+ afterRerouteId?: RerouteId
+ ): LLink | null {
+ // Allow legacy API support for searching target_slot by string, without mutating the input variables
+ let targetIndex: number | null
+
+ const { graph, outputs } = this
+ if (!graph) {
+ // could be connected before adding it to a graph
+ // due to link ids being associated with graphs
+ console.error(
+ "Connect: Error, node doesn't belong to any graph. Nodes must be added first to a graph before connecting them."
+ )
+ return null
+ }
+
+ // seek for the output slot
+ if (typeof slot === 'string') {
+ slot = this.findOutputSlot(slot)
+ if (slot == -1) {
+ if (LiteGraph.debug)
+ console.error(`Connect: Error, no slot of name ${slot}`)
+ return null
+ }
+ } else if (!outputs || slot >= outputs.length) {
+ if (LiteGraph.debug)
+ console.error('Connect: Error, slot number not found')
+ return null
+ }
+
+ if (target_node && typeof target_node === 'number') {
+ const nodeById = graph.getNodeById(target_node)
+ if (!nodeById) throw 'target node is null'
+
+ target_node = nodeById
+ }
+ if (!target_node) throw 'target node is null'
+
+ // avoid loopback
+ if (target_node == this) return null
+
+ // you can specify the slot by name
+ if (typeof target_slot === 'string') {
+ targetIndex = target_node.findInputSlot(target_slot)
+ if (targetIndex == -1) {
+ if (LiteGraph.debug)
+ console.error(`Connect: Error, no slot of name ${targetIndex}`)
+ return null
+ }
+ } else if (target_slot === LiteGraph.EVENT) {
+ // TODO: Events
+ if (LiteGraph.do_add_triggers_slots) {
+ target_node.changeMode(LGraphEventMode.ON_TRIGGER)
+ targetIndex = target_node.findInputSlot('onTrigger')
+ } else {
+ return null
+ }
+ } else if (typeof target_slot === 'number') {
+ targetIndex = target_slot
+ } else {
+ targetIndex = 0
+ }
+
+ // Allow target node to change slot
+ if (target_node.onBeforeConnectInput) {
+ // This way node can choose another slot (or make a new one?)
+ const requestedIndex = target_node.onBeforeConnectInput(
+ targetIndex,
+ target_slot
+ )
+ targetIndex = typeof requestedIndex === 'number' ? requestedIndex : null
+ }
+
+ if (
+ targetIndex === null ||
+ !target_node.inputs ||
+ targetIndex >= target_node.inputs.length
+ ) {
+ if (LiteGraph.debug)
+ console.error('Connect: Error, slot number not found')
+ return null
+ }
+
+ const input = target_node.inputs[targetIndex]
+ const output = outputs[slot]
+
+ if (!output) return null
+
+ if (output.links?.length) {
+ if (
+ output.type === LiteGraph.EVENT &&
+ !LiteGraph.allow_multi_output_for_events
+ ) {
+ graph.beforeChange()
+ this.disconnectOutput(slot)
+ }
+ }
+
+ const link = this.connectSlots(output, target_node, input, afterRerouteId)
+ return link ?? null
+ }
+
+ /**
+ * Connect two slots between two nodes
+ * @param output The output slot to connect
+ * @param inputNode The node that the input slot is on
+ * @param input The input slot to connect
+ * @param afterRerouteId The reroute ID to use for the link
+ * @returns The link that was created, or null if the connection was blocked
+ */
+ connectSlots(
+ output: INodeOutputSlot,
+ inputNode: LGraphNode,
+ input: INodeInputSlot,
+ afterRerouteId: RerouteId | undefined
+ ): LLink | null | undefined {
+ const { graph } = this
+ if (!graph) throw new NullGraphError()
+
+ const layoutMutations = useLayoutMutations()
+
+ const outputIndex = this.outputs.indexOf(output)
+ if (outputIndex === -1) {
+ console.warn('connectSlots: output not found')
+ return
+ }
+ const inputIndex = inputNode.inputs.indexOf(input)
+ if (inputIndex === -1) {
+ console.warn('connectSlots: input not found')
+ return
+ }
+
+ // check targetSlot and check connection types
+ if (!LiteGraph.isValidConnection(output.type, input.type)) {
+ this.setDirtyCanvas(false, true)
+ return null
+ }
+
+ // Allow nodes to block connection
+ if (
+ inputNode.onConnectInput?.(
+ inputIndex,
+ output.type,
+ output,
+ this,
+ outputIndex
+ ) === false
+ )
+ return null
+ if (
+ this.onConnectOutput?.(
+ outputIndex,
+ input.type,
+ input,
+ inputNode,
+ inputIndex
+ ) === false
+ )
+ return null
+
+ // if there is something already plugged there, disconnect
+ if (inputNode.inputs[inputIndex]?.link != null) {
+ graph.beforeChange()
+ inputNode.disconnectInput(inputIndex, true)
+ }
+
+ const maybeCommonType =
+ input.type && output.type && commonType(input.type, output.type)
+
+ const link = new LLink(
+ ++graph.state.lastLinkId,
+ maybeCommonType || input.type || output.type,
+ this.id,
+ outputIndex,
+ inputNode.id,
+ inputIndex,
+ afterRerouteId
+ )
+
+ // add to graph links list
+ graph._links.set(link.id, link)
+
+ // Register link in Layout Store for spatial tracking
+ layoutMutations.setSource(LayoutSource.Canvas)
+ layoutMutations.createLink(
+ link.id,
+ this.id,
+ outputIndex,
+ inputNode.id,
+ inputIndex
+ )
+
+ // connect in output
+ output.links ??= []
+ output.links.push(link.id)
+ // connect in input
+ const targetInput = inputNode.inputs[inputIndex]
+ targetInput.link = link.id
+ if (targetInput.widget) {
+ graph.trigger('node:slot-links:changed', {
+ nodeId: inputNode.id,
+ slotType: NodeSlotType.INPUT,
+ slotIndex: inputIndex,
+ connected: true,
+ linkId: link.id
+ })
+ }
+
+ // Reroutes
+ const reroutes = LLink.getReroutes(graph, link)
+ for (const reroute of reroutes) {
+ reroute.linkIds.add(link.id)
+ if (reroute.floating) reroute.floating = undefined
+ reroute._dragging = undefined
+ }
+
+ // If this is the terminus of a floating link, remove it
+ const lastReroute = reroutes.at(-1)
+ if (lastReroute) {
+ for (const linkId of lastReroute.floatingLinkIds) {
+ const link = graph.floatingLinks.get(linkId)
+ if (link?.parentId === lastReroute.id) {
+ graph.removeFloatingLink(link)
+ }
+ }
+ }
+ graph._version++
+
+ // link has been created now, so its updated
+ this.onConnectionsChange?.(
+ NodeSlotType.OUTPUT,
+ outputIndex,
+ true,
+ link,
+ output
+ )
+
+ inputNode.onConnectionsChange?.(
+ NodeSlotType.INPUT,
+ inputIndex,
+ true,
+ link,
+ input
+ )
+
+ this.setDirtyCanvas(false, true)
+ graph.afterChange()
+
+ return link
+ }
+
+ connectFloatingReroute(
+ pos: Point,
+ slot: INodeInputSlot | INodeOutputSlot,
+ afterRerouteId?: RerouteId
+ ): Reroute {
+ const { graph, id } = this
+ if (!graph) throw new NullGraphError()
+
+ // Assertion: It's either there or it isn't.
+ const inputIndex = this.inputs.indexOf(slot as INodeInputSlot)
+ const outputIndex = this.outputs.indexOf(slot as INodeOutputSlot)
+ if (inputIndex === -1 && outputIndex === -1) throw new Error('Invalid slot')
+
+ const slotType = outputIndex === -1 ? 'input' : 'output'
+
+ const reroute = graph.setReroute({
+ pos,
+ parentId: afterRerouteId,
+ linkIds: [],
+ floating: { slotType }
+ })
+
+ const parentReroute = graph.getReroute(afterRerouteId)
+ const fromLastFloatingReroute =
+ parentReroute?.floating?.slotType === 'output'
+
+ // Adding from an output, or a floating reroute that is NOT the tip of an existing floating chain
+ if (afterRerouteId == null || !fromLastFloatingReroute) {
+ const link = new LLink(
+ -1,
+ slot.type,
+ outputIndex === -1 ? -1 : id,
+ outputIndex,
+ inputIndex === -1 ? -1 : id,
+ inputIndex
+ )
+ link.parentId = reroute.id
+ graph.addFloatingLink(link)
+ return reroute
+ }
+
+ // Adding a new floating reroute from the tip of a floating chain.
+ if (!parentReroute)
+ throw new Error('[connectFloatingReroute] Parent reroute not found')
+
+ const link = parentReroute.getFloatingLinks('output')?.[0]
+ if (!link)
+ throw new Error('[connectFloatingReroute] Floating link not found')
+
+ reroute.floatingLinkIds.add(link.id)
+ link.parentId = reroute.id
+ parentReroute.floating = undefined
+ return reroute
+ }
+
+ /**
+ * disconnect one output to an specific node
+ * @param slot (could be the number of the slot or the string with the name of the slot)
+ * @param target_node the target node to which this slot is connected [Optional,
+ * if not target_node is specified all nodes will be disconnected]
+ * @returns if it was disconnected successfully
+ */
+ disconnectOutput(slot: string | number, target_node?: LGraphNode): boolean {
+ if (typeof slot === 'string') {
+ slot = this.findOutputSlot(slot)
+ if (slot == -1) {
+ if (LiteGraph.debug)
+ console.error(`Connect: Error, no slot of name ${slot}`)
+ return false
+ }
+ } else if (!this.outputs || slot >= this.outputs.length) {
+ if (LiteGraph.debug)
+ console.error('Connect: Error, slot number not found')
+ return false
+ }
+
+ // get output slot
+ const output = this.outputs[slot]
+ if (!output) return false
+
+ if (output._floatingLinks) {
+ for (const link of output._floatingLinks) {
+ if (link.hasOrigin(this.id, slot)) {
+ this.graph?.removeFloatingLink(link)
+ }
+ }
+ }
+
+ if (!output.links || output.links.length == 0) return false
+ const { links } = output
+
+ // one of the output links in this slot
+ const graph = this.graph
+ if (!graph) throw new NullGraphError()
+
+ if (target_node) {
+ const target =
+ typeof target_node === 'number'
+ ? graph.getNodeById(target_node)
+ : target_node
+ if (!target) throw 'Target Node not found'
+
+ for (const [i, link_id] of links.entries()) {
+ const link_info = graph._links.get(link_id)
+ if (link_info?.target_id != target.id) continue
+
+ // is the link we are searching for...
+ // remove here
+ links.splice(i, 1)
+ const input = target.inputs[link_info.target_slot]
+ // remove there
+ input.link = null
+ if (input.widget) {
+ graph.trigger('node:slot-links:changed', {
+ nodeId: target.id,
+ slotType: NodeSlotType.INPUT,
+ slotIndex: link_info.target_slot,
+ connected: false,
+ linkId: link_info.id
+ })
+ }
+
+ // remove the link from the links pool
+ link_info.disconnect(graph, 'input')
+ graph._version++
+
+ // link_info hasn't been modified so its ok
+ target.onConnectionsChange?.(
+ NodeSlotType.INPUT,
+ link_info.target_slot,
+ false,
+ link_info,
+ input
+ )
+ this.onConnectionsChange?.(
+ NodeSlotType.OUTPUT,
+ slot,
+ false,
+ link_info,
+ output
+ )
+
+ break
+ }
+ } else {
+ // all the links in this output slot
+ for (const link_id of links) {
+ const link_info = graph._links.get(link_id)
+ if (!link_info) continue
+ if (
+ link_info.target_id === SUBGRAPH_OUTPUT_ID &&
+ graph instanceof Subgraph
+ ) {
+ const targetSlot = graph.outputNode.slots[link_info.target_slot]
+ if (targetSlot) {
+ targetSlot.linkIds.length = 0
+ } else {
+ console.error('Missing subgraphOutput slot when disconnecting link')
+ }
+ }
+
+ const target = graph.getNodeById(link_info.target_id)
+ graph._version++
+
+ if (target) {
+ const input = target.inputs[link_info.target_slot]
+ // remove other side link
+ input.link = null
+ if (input.widget) {
+ graph.trigger('node:slot-links:changed', {
+ nodeId: target.id,
+ slotType: NodeSlotType.INPUT,
+ slotIndex: link_info.target_slot,
+ connected: false,
+ linkId: link_info.id
+ })
+ }
+
+ // link_info hasn't been modified so its ok
+ target.onConnectionsChange?.(
+ NodeSlotType.INPUT,
+ link_info.target_slot,
+ false,
+ link_info,
+ input
+ )
+ }
+ // remove the link from the links pool
+ link_info.disconnect(graph, 'input')
+
+ this.onConnectionsChange?.(
+ NodeSlotType.OUTPUT,
+ slot,
+ false,
+ link_info,
+ output
+ )
+ }
+ output.links = null
+ }
+
+ this.setDirtyCanvas(false, true)
+ return true
+ }
+
+ /**
+ * Disconnect one input
+ * @param slot Input slot index, or the name of the slot
+ * @param keepReroutes If `true`, reroutes will not be garbage collected.
+ * @returns true if disconnected successfully or already disconnected, otherwise false
+ */
+ disconnectInput(slot: number | string, keepReroutes?: boolean): boolean {
+ // Allow search by string
+ if (typeof slot === 'string') {
+ slot = this.findInputSlot(slot)
+ if (slot == -1) {
+ if (LiteGraph.debug)
+ console.error(`Connect: Error, no slot of name ${slot}`)
+ return false
+ }
+ } else if (!this.inputs || slot >= this.inputs.length) {
+ if (LiteGraph.debug) {
+ console.error('Connect: Error, slot number not found')
+ }
+ return false
+ }
+
+ const input = this.inputs[slot]
+ if (!input) {
+ console.error('disconnectInput: input not found', slot, this.inputs)
+ return false
+ }
+
+ const { graph } = this
+ if (!graph) throw new NullGraphError()
+
+ // Break floating links
+ if (input._floatingLinks?.size) {
+ for (const link of input._floatingLinks) {
+ graph.removeFloatingLink(link)
+ }
+ }
+
+ const link_id = this.inputs[slot].link
+ if (link_id != null) {
+ this.inputs[slot].link = null
+ if (input.widget) {
+ graph.trigger('node:slot-links:changed', {
+ nodeId: this.id,
+ slotType: NodeSlotType.INPUT,
+ slotIndex: slot,
+ connected: false,
+ linkId: link_id
+ })
+ }
+
+ // remove other side
+ const link_info = graph._links.get(link_id)
+ if (link_info) {
+ // Let SubgraphInput do the disconnect.
+ if (link_info.origin_id === -10 && 'inputNode' in graph) {
+ graph.inputNode._disconnectNodeInput(this, input, link_info)
+ return true
+ }
+
+ const target_node = graph.getNodeById(link_info.origin_id)
+ if (!target_node) {
+ console.error(
+ 'disconnectInput: output not found',
+ link_info.origin_slot
+ )
+ return false
+ }
+
+ const output = target_node.outputs[link_info.origin_slot]
+ if (!output?.links?.length) {
+ // Output not found - may have been removed
+ return false
+ }
+
+ // search in the inputs list for this link
+ let i = 0
+ for (const l = output.links.length; i < l; i++) {
+ if (output.links[i] == link_id) {
+ output.links.splice(i, 1)
+ break
+ }
+ }
+
+ link_info.disconnect(graph, keepReroutes ? 'output' : undefined)
+ if (graph) graph._version++
+
+ this.onConnectionsChange?.(
+ NodeSlotType.INPUT,
+ slot,
+ false,
+ link_info,
+ input
+ )
+ target_node.onConnectionsChange?.(
+ NodeSlotType.OUTPUT,
+ i,
+ false,
+ link_info,
+ output
+ )
+ }
+ }
+
+ this.setDirtyCanvas(false, true)
+ return true
+ }
+
+ /**
+ * @deprecated Use {@link getInputPos} or {@link getOutputPos} instead.
+ * returns the center of a connection point in canvas coords
+ * @param is_input true if if a input slot, false if it is an output
+ * @param slot_number (could be the number of the slot or the string with the name of the slot)
+ * @param out [optional] a place to store the output, to free garbage
+ * @returns the position
+ */
+ getConnectionPos(is_input: boolean, slot_number: number, out?: Point): Point {
+ out ||= [0, 0]
+
+ const {
+ pos: [nodeX, nodeY],
+ inputs,
+ outputs
+ } = this
+
+ if (this.flags.collapsed) {
+ const w = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH
+ out[0] = is_input ? nodeX : nodeX + w
+ out[1] = nodeY - LiteGraph.NODE_TITLE_HEIGHT * 0.5
+ return out
+ }
+
+ // weird feature that never got finished
+ if (is_input && slot_number == -1) {
+ out[0] = nodeX + LiteGraph.NODE_TITLE_HEIGHT * 0.5
+ out[1] = nodeY + LiteGraph.NODE_TITLE_HEIGHT * 0.5
+ return out
+ }
+
+ // hard-coded pos
+ const inputPos = inputs?.[slot_number]?.pos
+ const outputPos = outputs?.[slot_number]?.pos
+
+ if (is_input && inputPos) {
+ out[0] = nodeX + inputPos[0]
+ out[1] = nodeY + inputPos[1]
+ return out
+ } else if (!is_input && outputPos) {
+ out[0] = nodeX + outputPos[0]
+ out[1] = nodeY + outputPos[1]
+ return out
+ }
+
+ // default vertical slots
+ const offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5
+ const slotIndex = is_input
+ ? this.#defaultVerticalInputs.indexOf(this.inputs[slot_number])
+ : this.#defaultVerticalOutputs.indexOf(this.outputs[slot_number])
+
+ out[0] = is_input ? nodeX + offset : nodeX + this.size[0] + 1 - offset
+ out[1] =
+ nodeY +
+ (slotIndex + 0.7) * LiteGraph.NODE_SLOT_HEIGHT +
+ (this.constructor.slot_start_y || 0)
+ return out
+ }
+
+ /**
+ * @internal The inputs that are not positioned with absolute coordinates.
+ */
+ get #defaultVerticalInputs() {
+ return this.inputs.filter(
+ (slot) => !slot.pos && !(this.widgets?.length && isWidgetInputSlot(slot))
+ )
+ }
+
+ /**
+ * @internal The outputs that are not positioned with absolute coordinates.
+ */
+ get #defaultVerticalOutputs() {
+ return this.outputs.filter((slot: INodeOutputSlot) => !slot.pos)
+ }
+
+ /**
+ * Get the context needed for slot position calculations
+ * @internal
+ */
+ #getSlotPositionContext(): SlotPositionContext {
+ return {
+ nodeX: this.pos[0],
+ nodeY: this.pos[1],
+ nodeWidth: this.size[0],
+ nodeHeight: this.size[1],
+ collapsed: this.flags.collapsed ?? false,
+ collapsedWidth: this._collapsed_width,
+ slotStartY: this.constructor.slot_start_y,
+ inputs: this.inputs,
+ outputs: this.outputs,
+ widgets: this.widgets
+ }
+ }
+
+ /**
+ * Gets the position of an input slot, in graph co-ordinates.
+ *
+ * This method is preferred over the legacy {@link getConnectionPos} method.
+ * @param slot Input slot index
+ * @returns Position of the input slot
+ */
+ getInputPos(slot: number): Point {
+ return calculateInputSlotPos(this.#getSlotPositionContext(), slot)
+ }
+
+ /**
+ * Gets the position of an input slot, in graph co-ordinates.
+ * @param input The actual node input object
+ * @returns Position of the centre of the input slot in graph co-ordinates.
+ */
+ getInputSlotPos(input: INodeInputSlot): Point {
+ return calculateInputSlotPosFromSlot(this.#getSlotPositionContext(), input)
+ }
+
+ /**
+ * Gets the position of an output slot, in graph co-ordinates.
+ *
+ * This method is preferred over the legacy {@link getConnectionPos} method.
+ * @param outputSlotIndex Output slot index
+ * @returns Position of the output slot
+ */
+ getOutputPos(outputSlotIndex: number): Point {
+ return calculateOutputSlotPos(
+ this.#getSlotPositionContext(),
+ outputSlotIndex
+ )
+ }
+
+ /**
+ * Get slot position using layout tree if available, fallback to node's position * Unified implementation used by both LitegraphLinkAdapter and useLinkLayoutSync
+ * @param slotIndex The slot index
+ * @param isInput Whether this is an input slot
+ * @returns Position of the slot center in graph coordinates
+ */
+ getSlotPosition(slotIndex: number, isInput: boolean): Point {
+ return getSlotPosition(this, slotIndex, isInput)
+ }
+
+ /** @inheritdoc */
+ snapToGrid(snapTo: number): boolean {
+ return this.pinned ? false : snapPoint(this.pos, snapTo)
+ }
+
+ /** @see {@link snapToGrid} */
+ alignToGrid(): void {
+ this.snapToGrid(LiteGraph.CANVAS_GRID_SIZE)
+ }
+
+ /* Console output */
+ trace(msg: string): void {
+ this.console ||= []
+ this.console.push(msg)
+ // @ts-expect-error deprecated
+ if (this.console.length > LGraphNode.MAX_CONSOLE) this.console.shift()
+ }
+
+ /* Forces to redraw or the main canvas (LGraphNode) or the bg canvas (links) */
+ setDirtyCanvas(dirty_foreground: boolean, dirty_background?: boolean): void {
+ this.graph?.canvasAction((c) =>
+ c.setDirty(dirty_foreground, dirty_background)
+ )
+ }
+
+ loadImage(url: string): HTMLImageElement {
+ interface AsyncImageElement extends HTMLImageElement {
+ ready?: boolean
+ }
+
+ const img: AsyncImageElement = new Image()
+ img.src = LiteGraph.node_images_path + url
+ img.ready = false
+
+ const dirty = () => this.setDirtyCanvas(true)
+ img.addEventListener('load', function (this: AsyncImageElement) {
+ this.ready = true
+ dirty()
+ })
+ return img
+ }
+
+ /**
+ * Allows to get onMouseMove and onMouseUp events even if the mouse is out of focus
+ * @deprecated Use {@link LGraphCanvas.pointer} instead.
+ */
+ captureInput(v: boolean): void {
+ warnDeprecated(
+ '[DEPRECATED] captureInput will be removed in a future version. Please use LGraphCanvas.pointer (CanvasPointer) instead.'
+ )
+ if (!this.graph || !this.graph.list_of_graphcanvas) return
+
+ const list = this.graph.list_of_graphcanvas
+
+ for (const c of list) {
+ // releasing somebody elses capture?!
+ if (!v && c.node_capturing_input != this) continue
+
+ // change
+ c.node_capturing_input = v ? this : null
+ }
+ }
+
+ get collapsed() {
+ return !!this.flags.collapsed
+ }
+
+ get collapsible() {
+ return !this.pinned && this.constructor.collapsable !== false
+ }
+
+ /**
+ * Toggle node collapse (makes it smaller on the canvas)
+ */
+ collapse(force?: boolean): void {
+ if (!this.collapsible && !force) return
+ if (!this.graph) throw new NullGraphError()
+ this.graph._version++
+ this.flags.collapsed = !this.flags.collapsed
+ this.setDirtyCanvas(true, true)
+ }
+
+ /**
+ * Toggles advanced mode of the node, showing advanced widgets
+ */
+ toggleAdvanced() {
+ if (!this.widgets?.some((w) => w.advanced)) return
+ if (!this.graph) throw new NullGraphError()
+ this.graph._version++
+ this.showAdvanced = !this.showAdvanced
+ this.expandToFitContent()
+ this.setDirtyCanvas(true, true)
+ }
+
+ get pinned() {
+ return !!this.flags.pinned
+ }
+
+ /**
+ * Prevents the node being accidentally moved or resized by mouse interaction.
+ * Toggles pinned state if no value is provided.
+ */
+ pin(v?: boolean): void {
+ if (!this.graph) throw new NullGraphError()
+
+ this.graph._version++
+ this.flags.pinned = v ?? !this.flags.pinned
+ this.resizable = !this.pinned
+ if (!this.pinned) this.flags.pinned = undefined
+ }
+
+ unpin(): void {
+ this.pin(false)
+ }
+
+ localToScreen(x: number, y: number, dragAndScale: DragAndScale): Point {
+ return [
+ (x + this.pos[0]) * dragAndScale.scale + dragAndScale.offset[0],
+ (y + this.pos[1]) * dragAndScale.scale + dragAndScale.offset[1]
+ ]
+ }
+
+ get width() {
+ return this.collapsed
+ ? this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH
+ : this.size[0]
+ }
+
+ /**
+ * Returns the height of the node, including the title bar.
+ */
+ get height() {
+ return LiteGraph.NODE_TITLE_HEIGHT + this.bodyHeight
+ }
+
+ /**
+ * Returns the height of the node, excluding the title bar.
+ */
+ get bodyHeight() {
+ return this.collapsed ? 0 : this.size[1]
+ }
+
+ drawBadges(ctx: CanvasRenderingContext2D, { gap = 2 } = {}): void {
+ const badgeInstances = this.badges.map((badge) =>
+ badge instanceof LGraphBadge ? badge : badge()
+ )
+ const isLeftAligned = this.badgePosition === BadgePosition.TopLeft
+
+ let currentX = isLeftAligned
+ ? 0
+ : this.width -
+ badgeInstances.reduce(
+ (acc, badge) => acc + badge.getWidth(ctx) + gap,
+ 0
+ )
+ const y = -(LiteGraph.NODE_TITLE_HEIGHT + gap)
+
+ for (const badge of badgeInstances) {
+ badge.draw(ctx, currentX, y - badge.height)
+ currentX += badge.getWidth(ctx) + gap
+ }
+ }
+
+ /**
+ * Renders the node's title bar background
+ */
+ drawTitleBarBackground(
+ ctx: CanvasRenderingContext2D,
+ {
+ scale,
+ title_height = LiteGraph.NODE_TITLE_HEIGHT,
+ low_quality = false
+ }: DrawTitleOptions
+ ): void {
+ const fgcolor = this.renderingColor
+ const shape = this.renderingShape
+ const size = this.renderingSize
+
+ if (this.onDrawTitleBar) {
+ this.onDrawTitleBar(ctx, title_height, size, scale, fgcolor)
+ return
+ }
+
+ if (this.title_mode === TitleMode.TRANSPARENT_TITLE) {
+ return
+ }
+
+ if (this.collapsed) {
+ ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR
+ }
+
+ ctx.fillStyle = this.constructor.title_color || fgcolor
+ ctx.beginPath()
+
+ if (shape == RenderShape.BOX || low_quality) {
+ ctx.rect(0, -title_height, size[0], title_height)
+ } else if (shape == RenderShape.ROUND || shape == RenderShape.CARD) {
+ ctx.roundRect(
+ 0,
+ -title_height,
+ size[0],
+ title_height,
+ this.collapsed
+ ? [LiteGraph.ROUND_RADIUS]
+ : [LiteGraph.ROUND_RADIUS, LiteGraph.ROUND_RADIUS, 0, 0]
+ )
+ }
+ ctx.fill()
+ ctx.shadowColor = 'transparent'
+ }
+
+ /**
+ * Renders the node's title box, i.e. the dot in front of the title text that
+ * when clicked toggles the node's collapsed state. The term `title box` comes
+ * from the original LiteGraph implementation.
+ */
+ drawTitleBox(
+ ctx: CanvasRenderingContext2D,
+ {
+ scale,
+ low_quality = false,
+ title_height = LiteGraph.NODE_TITLE_HEIGHT,
+ box_size = 10
+ }: DrawTitleBoxOptions
+ ): void {
+ const size = this.renderingSize
+ const shape = this.renderingShape
+
+ if (this.onDrawTitleBox) {
+ this.onDrawTitleBox(ctx, title_height, size, scale)
+ return
+ }
+
+ if (
+ [RenderShape.ROUND, RenderShape.CIRCLE, RenderShape.CARD].includes(shape)
+ ) {
+ if (low_quality) {
+ ctx.fillStyle = 'black'
+ ctx.beginPath()
+ ctx.arc(
+ title_height * 0.5,
+ title_height * -0.5,
+ box_size * 0.5 + 1,
+ 0,
+ Math.PI * 2
+ )
+ ctx.fill()
+ }
+
+ ctx.fillStyle = this.renderingBoxColor
+ if (low_quality) {
+ ctx.fillRect(
+ title_height * 0.5 - box_size * 0.5,
+ title_height * -0.5 - box_size * 0.5,
+ box_size,
+ box_size
+ )
+ } else {
+ ctx.beginPath()
+ ctx.arc(
+ title_height * 0.5,
+ title_height * -0.5,
+ box_size * 0.5,
+ 0,
+ Math.PI * 2
+ )
+ ctx.fill()
+ }
+ } else {
+ if (low_quality) {
+ ctx.fillStyle = 'black'
+ ctx.fillRect(
+ (title_height - box_size) * 0.5 - 1,
+ (title_height + box_size) * -0.5 - 1,
+ box_size + 2,
+ box_size + 2
+ )
+ }
+ ctx.fillStyle = this.renderingBoxColor
+ ctx.fillRect(
+ (title_height - box_size) * 0.5,
+ (title_height + box_size) * -0.5,
+ box_size,
+ box_size
+ )
+ }
+ }
+
+ /**
+ * Renders the node's title text.
+ */
+ drawTitleText(
+ ctx: CanvasRenderingContext2D,
+ {
+ scale,
+ default_title_color,
+ low_quality = false,
+ title_height = LiteGraph.NODE_TITLE_HEIGHT
+ }: DrawTitleTextOptions
+ ): void {
+ const size = this.renderingSize
+ const selected = this.selected
+
+ if (this.onDrawTitleText) {
+ this.onDrawTitleText(
+ ctx,
+ title_height,
+ size,
+ scale,
+ this.titleFontStyle,
+ selected
+ )
+ return
+ }
+
+ // Don't render title text if low quality
+ if (low_quality) {
+ return
+ }
+
+ ctx.font = this.titleFontStyle
+ const rawTitle = this.getTitle() ?? `❌ ${this.type}`
+ const title = String(rawTitle) + (this.pinned ? '📌' : '')
+ if (title) {
+ if (selected) {
+ ctx.fillStyle = LiteGraph.NODE_SELECTED_TITLE_COLOR
+ } else {
+ ctx.fillStyle = this.constructor.title_text_color || default_title_color
+ }
+
+ // Calculate available width for title
+ let availableWidth = size[0] - title_height * 2 // Basic margins
+
+ // Subtract space for title buttons
+ if (this.title_buttons?.length > 0) {
+ let buttonsWidth = 0
+ const savedFont = ctx.font // Save current font
+ for (const button of this.title_buttons) {
+ if (button.visible) {
+ buttonsWidth += button.getWidth(ctx) + 2 // button width + gap
+ }
+ }
+ ctx.font = savedFont // Restore font after button measurements
+ if (buttonsWidth > 0) {
+ buttonsWidth -= 20 // Reduce by empty padding
+ availableWidth -= buttonsWidth
+ }
+ }
+
+ // Truncate title if needed
+ let displayTitle = title
+
+ if (this.collapsed) {
+ // For collapsed nodes, limit to 20 chars as before
+ displayTitle = title.substr(0, 20)
+ } else if (availableWidth > 0) {
+ // For regular nodes, truncate based on available width
+ displayTitle = truncateText(ctx, title, availableWidth)
+ }
+
+ ctx.textAlign = 'left'
+ ctx.fillText(
+ displayTitle,
+ title_height,
+ LiteGraph.NODE_TITLE_TEXT_Y - title_height
+ )
+ }
+ }
+
+ /**
+ * Attempts to gracefully bypass this node in all of its connections by reconnecting all links.
+ *
+ * Each input is checked against each output. This is done on a matching index basis, i.e. input 3 -> output 3.
+ * If there are any input links remaining,
+ * and {@link flags}.{@link INodeFlags.keepAllLinksOnBypass keepAllLinksOnBypass} is `true`,
+ * each input will check for outputs that match, and take the first one that matches
+ * `true`: Try the index matching first, then every input to every output.
+ * `false`: Only matches indexes, e.g. input 3 to output 3.
+ *
+ * If {@link flags}.{@link INodeFlags.keepAllLinksOnBypass keepAllLinksOnBypass} is `undefined`, it will fall back to
+ * the static {@link keepAllLinksOnBypass}.
+ * @returns `true` if any new links were established, otherwise `false`.
+ * @todo Decision: Change API to return array of new links instead?
+ */
+ connectInputToOutput(): boolean | undefined {
+ const { inputs, outputs, graph } = this
+ if (!inputs || !outputs) return
+ if (!graph) throw new NullGraphError()
+
+ const { _links } = graph
+ let madeAnyConnections = false
+
+ // First pass: only match exactly index-to-index
+ for (const [index, input] of inputs.entries()) {
+ if (input.link == null) continue
+
+ const output = outputs[index]
+ if (!output || !LiteGraph.isValidConnection(input.type, output.type))
+ continue
+
+ const inLink = _links.get(input.link)
+ if (!inLink) continue
+ const inNode = graph.getNodeById(inLink?.origin_id)
+ if (!inNode) continue
+
+ bypassAllLinks(output, inNode, inLink, graph)
+ }
+ // Configured to only use index-to-index matching
+ if (!(this.flags.keepAllLinksOnBypass ?? LGraphNode.keepAllLinksOnBypass))
+ return madeAnyConnections
+
+ // Second pass: match any remaining links
+ for (const input of inputs) {
+ if (input.link == null) continue
+
+ const inLink = _links.get(input.link)
+ if (!inLink) continue
+ const inNode = graph.getNodeById(inLink?.origin_id)
+ if (!inNode) continue
+
+ for (const output of outputs) {
+ if (!LiteGraph.isValidConnection(input.type, output.type)) continue
+
+ bypassAllLinks(output, inNode, inLink, graph)
+ break
+ }
+ }
+ return madeAnyConnections
+
+ function bypassAllLinks(
+ output: INodeOutputSlot,
+ inNode: LGraphNode,
+ inLink: LLink,
+ graph: LGraph
+ ) {
+ const outLinks = output.links
+ ?.map((x) => _links.get(x))
+ .filter((x) => !!x)
+ if (!outLinks?.length) return
+
+ for (const outLink of outLinks) {
+ const outNode = graph.getNodeById(outLink.target_id)
+ if (!outNode) continue
+
+ const result = inNode.connect(
+ inLink.origin_slot,
+ outNode,
+ outLink.target_slot,
+ inLink.parentId
+ )
+ madeAnyConnections ||= !!result
+ }
+ }
+ }
+
+ /**
+ * Returns `true` if the widget is visible, otherwise `false`.
+ */
+ isWidgetVisible(widget: IBaseWidget): boolean {
+ const isHidden =
+ this.collapsed || widget.hidden || (widget.advanced && !this.showAdvanced)
+ return !isHidden
+ }
+
+ updateComputedDisabled() {
+ if (!this.widgets) return
+ for (const widget of this.widgets)
+ widget.computedDisabled =
+ widget.disabled || this.getSlotFromWidget(widget)?.link != null
+ }
+
+ drawWidgets(
+ ctx: CanvasRenderingContext2D,
+ { lowQuality = false, editorAlpha = 1 }: DrawWidgetsOptions
+ ): void {
+ if (!this.widgets) return
+
+ const nodeWidth = this.size[0]
+ const { widgets } = this
+ const H = LiteGraph.NODE_WIDGET_HEIGHT
+ const showText = !lowQuality
+ ctx.save()
+ ctx.globalAlpha = editorAlpha
+
+ this.updateComputedDisabled()
+ for (const widget of widgets) {
+ if (!this.isWidgetVisible(widget)) continue
+
+ const { y } = widget
+ const outlineColour = widget.advanced
+ ? LiteGraph.WIDGET_ADVANCED_OUTLINE_COLOR
+ : LiteGraph.WIDGET_OUTLINE_COLOR
+
+ widget.last_y = y
+
+ ctx.strokeStyle = outlineColour
+ ctx.fillStyle = '#222'
+ ctx.textAlign = 'left'
+ if (widget.computedDisabled) ctx.globalAlpha *= 0.5
+ const width = widget.width || nodeWidth
+
+ if (typeof widget.draw === 'function') {
+ widget.draw(ctx, this, width, y, H, lowQuality)
+ } else {
+ toConcreteWidget(widget, this, false)?.drawWidget(ctx, {
+ width,
+ showText
+ })
+ }
+ ctx.globalAlpha = editorAlpha
+ }
+ ctx.restore()
+ }
+
+ /**
+ * When {@link LGraphNode.collapsed} is `true`, this method draws the node's collapsed slots.
+ */
+ drawCollapsedSlots(ctx: CanvasRenderingContext2D): void {
+ // Render the first connected slot only.
+ for (const slot of this.#concreteInputs) {
+ if (slot.link != null) {
+ slot.drawCollapsed(ctx)
+ break
+ }
+ }
+ for (const slot of this.#concreteOutputs) {
+ if (slot.links?.length) {
+ slot.drawCollapsed(ctx)
+ break
+ }
+ }
+ }
+
+ get slots(): (INodeInputSlot | INodeOutputSlot)[] {
+ return [...this.inputs, ...this.outputs]
+ }
+
+ #measureSlot(
+ slot: NodeInputSlot | NodeOutputSlot,
+ slotIndex: number,
+ isInput: boolean
+ ): void {
+ const pos = isInput
+ ? this.getInputPos(slotIndex)
+ : this.getOutputPos(slotIndex)
+
+ slot.boundingRect[0] = pos[0] - LiteGraph.NODE_SLOT_HEIGHT * 0.5
+ slot.boundingRect[1] = pos[1] - LiteGraph.NODE_SLOT_HEIGHT * 0.5
+ slot.boundingRect[2] = slot.isWidgetInputSlot
+ ? BaseWidget.margin
+ : LiteGraph.NODE_SLOT_HEIGHT
+ slot.boundingRect[3] = LiteGraph.NODE_SLOT_HEIGHT
+ }
+
+ #measureSlots(): ReadOnlyRect | null {
+ const slots: (NodeInputSlot | NodeOutputSlot)[] = []
+
+ for (const [slotIndex, slot] of this.#concreteInputs.entries()) {
+ // Unrecognized nodes (Nodes with error) has inputs but no widgets. Treat
+ // converted inputs as normal inputs.
+ /** Widget input slots are handled in {@link layoutWidgetInputSlots} */
+ if (this.widgets?.length && isWidgetInputSlot(slot)) continue
+
+ this.#measureSlot(slot, slotIndex, true)
+ slots.push(slot)
+ }
+ for (const [slotIndex, slot] of this.#concreteOutputs.entries()) {
+ this.#measureSlot(slot, slotIndex, false)
+ slots.push(slot)
+ }
+
+ return slots.length ? createBounds(slots, 0) : null
+ }
+
+ #getMouseOverSlot(slot: INodeSlot): INodeSlot | null {
+ const isInput = isINodeInputSlot(slot)
+ const mouseOverId = this.mouseOver?.[isInput ? 'inputId' : 'outputId'] ?? -1
+ if (mouseOverId === -1) {
+ return null
+ }
+ return isInput ? this.inputs[mouseOverId] : this.outputs[mouseOverId]
+ }
+
+ #isMouseOverSlot(slot: INodeSlot): boolean {
+ return this.#getMouseOverSlot(slot) === slot
+ }
+
+ #isMouseOverWidget(widget: IBaseWidget | undefined): boolean {
+ if (!widget) return false
+ return this.mouseOver?.overWidget === widget
+ }
+
+ /**
+ * Returns the input slot that is associated with the given widget.
+ */
+ getSlotFromWidget(
+ widget: IBaseWidget | undefined
+ ): INodeInputSlot | undefined {
+ if (widget)
+ return this.inputs.find(
+ (slot) => isWidgetInputSlot(slot) && slot.widget.name === widget.name
+ )
+ }
+
+ /**
+ * Returns the widget that is associated with the given input slot.
+ */
+ getWidgetFromSlot(slot: INodeInputSlot): IBaseWidget | undefined {
+ if (!isWidgetInputSlot(slot)) return
+ return this.widgets?.find((w) => w.name === slot.widget.name)
+ }
+
+ /**
+ * Draws the node's input and output slots.
+ */
+ drawSlots(
+ ctx: CanvasRenderingContext2D,
+ { fromSlot, colorContext, editorAlpha, lowQuality }: DrawSlotsOptions
+ ) {
+ for (const slot of [...this.#concreteInputs, ...this.#concreteOutputs]) {
+ const isValidTarget = fromSlot && slot.isValidTarget(fromSlot)
+ const isMouseOverSlot = this.#isMouseOverSlot(slot)
+
+ // change opacity of incompatible slots when dragging a connection
+ const isValid = !fromSlot || isValidTarget
+ const highlight = isValid && isMouseOverSlot
+
+ // Show slot if it's not a widget input slot
+ // or if it's a widget input slot and satisfies one of the following:
+ // - the mouse is over the widget
+ // - the slot is valid during link drop
+ // - the slot is connected
+ if (
+ isMouseOverSlot ||
+ isValidTarget ||
+ !slot.isWidgetInputSlot ||
+ this.#isMouseOverWidget(this.getWidgetFromSlot(slot)) ||
+ slot.isConnected ||
+ slot.alwaysVisible
+ ) {
+ ctx.globalAlpha = isValid ? editorAlpha : 0.4 * editorAlpha
+ slot.draw(ctx, {
+ colorContext,
+ lowQuality,
+ highlight
+ })
+ }
+ }
+ }
+
+ /**
+ * Arranges the node's widgets vertically.
+ * Sets following properties on each widget:
+ * - {@link IBaseWidget.computedHeight}
+ * - {@link IBaseWidget.y}
+ * @param widgetStartY The y-coordinate of the first widget
+ */
+ #arrangeWidgets(widgetStartY: number): void {
+ if (!this.widgets || !this.widgets.length) return
+
+ const bodyHeight = this.bodyHeight
+ const startY =
+ this.widgets_start_y ?? (this.widgets_up ? 0 : widgetStartY) + 2
+
+ let freeSpace = bodyHeight - startY
+
+ // Collect fixed height widgets first
+ let fixedWidgetHeight = 0
+ const growableWidgets: {
+ minHeight: number
+ prefHeight?: number
+ w: IBaseWidget
+ }[] = []
+
+ const visibleWidgets = this.widgets.filter((w) => !w.hidden)
+
+ for (const w of visibleWidgets) {
+ if (w.computeSize) {
+ const height = w.computeSize()[1] + 4
+ w.computedHeight = height
+ fixedWidgetHeight += height
+ } else if (w.computeLayoutSize) {
+ const { minHeight, maxHeight } = w.computeLayoutSize(this)
+ growableWidgets.push({
+ minHeight,
+ prefHeight: maxHeight,
+ w
+ })
+ } else {
+ const height = LiteGraph.NODE_WIDGET_HEIGHT + 4
+ w.computedHeight = height
+ fixedWidgetHeight += height
+ }
+ }
+
+ // Calculate remaining space for DOM widgets
+ freeSpace -= fixedWidgetHeight
+ this.freeWidgetSpace = freeSpace
+
+ // Prepare space requests for distribution
+ const spaceRequests = growableWidgets.map((d) => ({
+ minSize: d.minHeight,
+ maxSize: d.prefHeight
+ }))
+
+ // Distribute space among DOM widgets
+ const allocations = distributeSpace(Math.max(0, freeSpace), spaceRequests)
+
+ // Apply computed heights
+ for (const [i, d] of growableWidgets.entries()) {
+ d.w.computedHeight = allocations[i]
+ }
+
+ // Position widgets
+ let y = startY
+ for (const w of visibleWidgets) {
+ w.y = y
+ y += w.computedHeight ?? 0
+ }
+
+ if (!this.graph) throw new NullGraphError()
+
+ // Grow the node if necessary.
+ // Ref: https://github.com/Comfy-Org/ComfyUI_frontend/issues/2652
+ // TODO: Move the layout logic before drawing of the node shape, so we don't
+ // need to trigger extra round of rendering.
+ if (y > bodyHeight) {
+ this.setSize([this.size[0], y])
+ this.graph.setDirtyCanvas(false, true)
+ }
+ }
+
+ /**
+ * Arranges the layout of the node's widget input slots.
+ */
+ #arrangeWidgetInputSlots(): void {
+ if (!this.widgets) return
+
+ const slotByWidgetName = new Map<
+ string,
+ INodeInputSlot & { index: number }
+ >()
+
+ for (const [i, slot] of this.inputs.entries()) {
+ if (!isWidgetInputSlot(slot)) continue
+
+ slotByWidgetName.set(slot.widget.name, { ...slot, index: i })
+ }
+ if (!slotByWidgetName.size) return
+
+ // Only set custom pos if not using Vue positioning
+ // Vue positioning calculates widget slot positions dynamically
+ if (!LiteGraph.vueNodesMode) {
+ for (const widget of this.widgets) {
+ const slot = slotByWidgetName.get(widget.name)
+ if (!slot) continue
+
+ const actualSlot = this.#concreteInputs[slot.index]
+ const offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5
+ actualSlot.pos = [offset, widget.y + offset]
+ this.#measureSlot(actualSlot, slot.index, true)
+ }
+ } else {
+ // For Vue positioning, just measure the slots without setting pos
+ for (const widget of this.widgets) {
+ const slot = slotByWidgetName.get(widget.name)
+ if (!slot) continue
+
+ this.#measureSlot(this.#concreteInputs[slot.index], slot.index, true)
+ }
+ }
+ }
+
+ /**
+ * @internal Sets the internal concrete slot arrays, ensuring they are instances of
+ * {@link NodeInputSlot} or {@link NodeOutputSlot}.
+ *
+ * A temporary workaround until duck-typed inputs and outputs
+ * have been removed from the ecosystem.
+ */
+ _setConcreteSlots(): void {
+ this.#concreteInputs = this.inputs.map((slot) =>
+ toClass(NodeInputSlot, slot, this)
+ )
+ this.#concreteOutputs = this.outputs.map((slot) =>
+ toClass(NodeOutputSlot, slot, this)
+ )
+ }
+
+ /**
+ * Arranges node elements in preparation for rendering (slots & widgets).
+ */
+ arrange(): void {
+ const slotsBounds = this.#measureSlots()
+ const widgetStartY = slotsBounds
+ ? slotsBounds[1] + slotsBounds[3] - this.pos[1]
+ : 0
+ this.#arrangeWidgets(widgetStartY)
+ this.#arrangeWidgetInputSlots()
+ }
+
+ /**
+ * Draws a progress bar on the node.
+ * @param ctx The canvas context to draw on
+ */
+ drawProgressBar(ctx: CanvasRenderingContext2D): void {
+ if (!this.progress) return
+
+ const originalFillStyle = ctx.fillStyle
+ ctx.fillStyle = 'green'
+ ctx.fillRect(0, 0, this.width * this.progress, 6)
+ ctx.fillStyle = originalFillStyle
+ }
+}
diff --git a/docs/hel-892/setget-reference/1.37.11__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts b/docs/hel-892/setget-reference/1.37.11__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts
new file mode 100644
index 00000000..9e9454a8
--- /dev/null
+++ b/docs/hel-892/setget-reference/1.37.11__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts
@@ -0,0 +1,408 @@
+import type { LGraph } from '@/lib/litegraph/src/LGraph'
+import type { LGraphNode, NodeId } from '@/lib/litegraph/src/LGraphNode'
+import { InvalidLinkError } from '@/lib/litegraph/src/infrastructure/InvalidLinkError'
+import { NullGraphError } from '@/lib/litegraph/src/infrastructure/NullGraphError'
+import { RecursionError } from '@/lib/litegraph/src/infrastructure/RecursionError'
+import { SlotIndexError } from '@/lib/litegraph/src/infrastructure/SlotIndexError'
+import type {
+ CallbackParams,
+ CallbackReturn,
+ ISlotType
+} from '@/lib/litegraph/src/interfaces'
+import { LGraphEventMode, LiteGraph } from '@/lib/litegraph/src/litegraph'
+
+import type { Subgraph } from './Subgraph'
+import type { SubgraphNode } from './SubgraphNode'
+
+export type ExecutionId = string
+
+/**
+ * Interface describing the data transfer objects used when compiling a graph for execution.
+ */
+export type ExecutableLGraphNode = Omit<
+ ExecutableNodeDTO,
+ 'graph' | 'node' | 'subgraphNode'
+>
+
+/**
+ * The end result of resolving a DTO input.
+ * When a widget value is returned, {@link widgetInfo} is present and {@link origin_slot} is `-1`.
+ */
+type ResolvedInput = {
+ /** DTO for the node that the link originates from. */
+ node: ExecutableLGraphNode
+ /** Full unique execution ID of the node that the link originates from. In the case of a widget value, this is the ID of the subgraph node. */
+ origin_id: ExecutionId
+ /** The slot index of the output on the node that the link originates from. `-1` when widget value is set. */
+ origin_slot: number
+ /** Boxed widget value (e.g. for widgets). If this box is `undefined`, then an input link is connected, and widget values from the subgraph node are ignored. */
+ widgetInfo?: { value: unknown }
+}
+
+/**
+ * Concrete implementation of {@link ExecutableLGraphNode}.
+ * @remarks This is the class that is used to create the data transfer objects for executable nodes.
+ */
+export class ExecutableNodeDTO implements ExecutableLGraphNode {
+ applyToGraph?(
+ ...args: CallbackParams
+ ): CallbackReturn
+
+ /** The graph that this node is a part of. */
+ readonly graph: LGraph | Subgraph
+
+ inputs: { linkId: number | null; name: string; type: ISlotType }[]
+
+ /** Backing field for {@link id}. */
+ #id: ExecutionId
+
+ /**
+ * The path to the actual node through subgraph instances, represented as a list of all subgraph node IDs (instances),
+ * followed by the actual original node ID within the subgraph. Each segment is separated by `:`.
+ *
+ * e.g. `1:2:3`:
+ * - `1` is the node ID of the first subgraph node in the parent workflow
+ * - `2` is the node ID of the second subgraph node in the first subgraph
+ * - `3` is the node ID of the actual node in the subgraph definition
+ */
+ get id() {
+ return this.#id
+ }
+
+ 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(
+ /** The actual node that this DTO wraps. */
+ readonly node: LGraphNode | SubgraphNode,
+ /** A list of subgraph instance node IDs from the root graph to the containing instance. @see {@link id} */
+ readonly subgraphNodePath: readonly NodeId[],
+ /** A flattened map of all DTOs in this node network. Subgraph instances have been expanded into their inner nodes. */
+ readonly nodesByExecutionId: Map,
+ /** The actual subgraph instance that contains this node, otherwise undefined. */
+ readonly subgraphNode?: SubgraphNode
+ ) {
+ if (!node.graph) throw new NullGraphError()
+
+ // Set the internal ID of the DTO
+ this.#id = [...this.subgraphNodePath, this.node.id].join(':')
+ this.graph = node.graph
+ this.inputs = this.node.inputs.map((x) => ({
+ linkId: x.link,
+ name: x.name,
+ type: x.type
+ }))
+
+ // Only create a wrapper if the node has an applyToGraph method
+ if (this.node.applyToGraph) {
+ this.applyToGraph = (...args) => this.node.applyToGraph?.(...args)
+ }
+ }
+
+ /** Returns either the DTO itself, or the DTOs of the inner nodes of the subgraph. */
+ getInnerNodes(): ExecutableLGraphNode[] {
+ return this.node.isSubgraphNode()
+ ? this.node.getInnerNodes(this.nodesByExecutionId, this.subgraphNodePath)
+ : [this]
+ }
+
+ /**
+ * Resolves the executable node & link IDs for a given input slot.
+ * @param slot The slot index of the input.
+ * @param visited Leave empty unless overriding this method.
+ * A set of unique IDs, used to guard against infinite recursion.
+ * If overriding, ensure that the set is passed on all recursive calls.
+ * @returns The node and the origin ID / slot index of the output.
+ */
+ resolveInput(
+ slot: number,
+ visited = new Set(),
+ type?: ISlotType
+ ): ResolvedInput | undefined {
+ const uniqueId = `${this.subgraphNode?.subgraph.id}:${this.node.id}[I]${slot}`
+ if (visited.has(uniqueId)) {
+ const nodeInfo = `${this.node.id}${this.node.title ? ` (${this.node.title})` : ''}`
+ const pathInfo =
+ this.subgraphNodePath.length > 0
+ ? ` at path ${this.subgraphNodePath.join(':')}`
+ : ''
+ throw new RecursionError(
+ `Circular reference detected while resolving input ${slot} of node ${nodeInfo}${pathInfo}. ` +
+ `This creates an infinite loop in link resolution. UniqueID: [${uniqueId}]`
+ )
+ }
+ visited.add(uniqueId)
+
+ const input = this.inputs.at(slot)
+ if (!input)
+ throw new SlotIndexError(
+ `No input found for flattened id [${this.id}] slot [${slot}]`
+ )
+
+ // Nothing connected
+ if (input.linkId == null) return
+
+ const link = this.graph.getLink(input.linkId)
+ if (!link)
+ throw new InvalidLinkError(
+ `No link found in parent graph for id [${this.id}] slot [${slot}] ${input.name}`
+ )
+
+ const { subgraphNode } = this
+
+ // Link goes up and out of this subgraph
+ if (subgraphNode && link.originIsIoNode) {
+ const subgraphNodeInput = subgraphNode.inputs.at(link.origin_slot)
+ if (!subgraphNodeInput)
+ throw new SlotIndexError(
+ `No input found for slot [${link.origin_slot}] ${input.name}`
+ )
+
+ // Nothing connected
+ const linkId = subgraphNodeInput.link
+ if (linkId == null) {
+ const widget = subgraphNode.getWidgetFromSlot(subgraphNodeInput)
+ if (!widget) return
+
+ // Special case: SubgraphNode widget.
+ return {
+ node: this,
+ origin_id: this.id,
+ origin_slot: -1,
+ widgetInfo: { value: widget.value }
+ }
+ }
+
+ const outerLink = subgraphNode.graph.getLink(linkId)
+ if (!outerLink)
+ throw new InvalidLinkError(
+ `No outer link found for slot [${link.origin_slot}] ${input.name}`
+ )
+
+ const subgraphNodeExecutionId = this.subgraphNodePath.join(':')
+ const subgraphNodeDto = this.nodesByExecutionId.get(
+ subgraphNodeExecutionId
+ )
+ if (!subgraphNodeDto)
+ throw new Error(
+ `No subgraph node DTO found for id [${subgraphNodeExecutionId}]`
+ )
+
+ return subgraphNodeDto.resolveInput(outerLink.target_slot, visited)
+ }
+
+ // Not part of a subgraph; use the original link
+ const outputNode = this.graph.getNodeById(link.origin_id)
+ if (!outputNode)
+ throw new InvalidLinkError(
+ `No input node found for id [${this.id}] slot [${slot}] ${input.name}`
+ )
+
+ const outputNodeExecutionId = [
+ ...this.subgraphNodePath,
+ outputNode.id
+ ].join(':')
+ const outputNodeDto = this.nodesByExecutionId.get(outputNodeExecutionId)
+ if (!outputNodeDto)
+ throw new Error(
+ `No output node DTO found for id [${outputNodeExecutionId}]`
+ )
+
+ return outputNodeDto.resolveOutput(
+ link.origin_slot,
+ type ?? input.type,
+ visited
+ )
+ }
+
+ /**
+ * Determines whether this output is a valid endpoint for a link (non-virtual, non-bypass).
+ * @param slot The slot index of the output.
+ * @param type The type of the input
+ * @param visited A set of unique IDs to guard against infinite recursion. See {@link resolveInput}.
+ * @returns The node and the origin ID / slot index of the output.
+ */
+ resolveOutput(
+ slot: number,
+ type: ISlotType,
+ visited: Set
+ ): ResolvedInput | undefined {
+ const uniqueId = `${this.subgraphNode?.subgraph.id}:${this.node.id}[O]${slot}`
+ if (visited.has(uniqueId)) {
+ const nodeInfo = `${this.node.id}${this.node.title ? ` (${this.node.title})` : ''}`
+ const pathInfo =
+ this.subgraphNodePath.length > 0
+ ? ` at path ${this.subgraphNodePath.join(':')}`
+ : ''
+ throw new RecursionError(
+ `Circular reference detected while resolving output ${slot} of node ${nodeInfo}${pathInfo}. ` +
+ `This creates an infinite loop in link resolution. UniqueID: [${uniqueId}]`
+ )
+ }
+ visited.add(uniqueId)
+
+ // Upstreamed: Bypass nodes are bypassed using the first input with matching type
+ if (this.mode === LGraphEventMode.BYPASS) {
+ // Bypass nodes by finding first input with matching type
+ const matchingIndex = this.#getBypassSlotIndex(slot, type)
+
+ // No input types match - bypass not possible
+ if (matchingIndex === -1) {
+ console.warn(
+ `[ExecutableNodeDTO.resolveOutput] No input types match type [${type}] for id [${this.id}] slot [${slot}]`,
+ this
+ )
+ return
+ }
+
+ return this.resolveInput(matchingIndex, visited)
+ }
+
+ const { node } = this
+ if (node.isSubgraphNode())
+ return this.#resolveSubgraphOutput(slot, type, visited)
+
+ if (node.isVirtualNode) {
+ const virtualLink = this.node.getInputLink(slot)
+ if (virtualLink) {
+ const { inputNode } = virtualLink.resolve(this.graph)
+ if (!inputNode)
+ throw new InvalidLinkError(
+ `Virtual node failed to resolve parent [${this.id}] slot [${slot}]`
+ )
+
+ const inputNodeExecutionId = [
+ ...this.subgraphNodePath,
+ inputNode.id
+ ].join(':')
+ const inputNodeDto = this.nodesByExecutionId.get(inputNodeExecutionId)
+ if (!inputNodeDto)
+ throw new Error(`No input node DTO found for id [${inputNode.id}]`)
+
+ return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type)
+ }
+
+ // Virtual nodes without a matching input should be discarded.
+ return
+ }
+
+ return {
+ node: this,
+ origin_id: this.id,
+ origin_slot: slot
+ }
+ }
+
+ /**
+ * Finds the index of the input slot on this node that matches the given output {@link slot} index.
+ * Used when bypassing nodes.
+ * @param slot The output slot index on this node
+ * @param type The type of the final target input (so type list matches are accurate)
+ * @returns The index of the input slot on this node, otherwise `-1`.
+ */
+ #getBypassSlotIndex(slot: number, type: ISlotType) {
+ const { inputs } = this
+ const oppositeInput = inputs[slot]
+ const outputType = this.node.outputs[slot].type
+
+ // Any type short circuit - match slot ID, fallback to first slot
+ if (type === '*' || type === '') {
+ return inputs.length > slot ? slot : 0
+ }
+
+ // Prefer input with the same slot ID
+ if (
+ oppositeInput &&
+ LiteGraph.isValidConnection(oppositeInput.type, outputType) &&
+ LiteGraph.isValidConnection(oppositeInput.type, type)
+ ) {
+ return slot
+ }
+
+ // Preserve legacy behaviour; use exact match first.
+ const exactMatch = inputs.findIndex((input) => input.type === type)
+ if (exactMatch !== -1) return exactMatch
+
+ // Find first matching slot - prefer exact type
+ return inputs.findIndex(
+ (input) =>
+ LiteGraph.isValidConnection(input.type, outputType) &&
+ LiteGraph.isValidConnection(input.type, type)
+ )
+ }
+
+ /**
+ * Resolves the link inside a subgraph node, from the subgraph IO node to the node inside the subgraph.
+ * @param slot The slot index of the output on the subgraph node.
+ * @param visited A set of unique IDs to guard against infinite recursion. See {@link resolveInput}.
+ * @returns A DTO for the node, and the origin ID / slot index of the output.
+ */
+ #resolveSubgraphOutput(
+ slot: number,
+ type: ISlotType,
+ visited: Set
+ ): ResolvedInput | undefined {
+ const { node } = this
+ const output = node.outputs.at(slot)
+
+ if (!output)
+ throw new SlotIndexError(
+ `No output found for flattened id [${this.id}] slot [${slot}]`
+ )
+ if (!node.isSubgraphNode())
+ throw new TypeError(`Node is not a subgraph node: ${node.id}`)
+
+ // Link inside the subgraph
+ const innerResolved = node.resolveSubgraphOutputLink(slot)
+ if (!innerResolved) return
+
+ const innerNode = innerResolved.outputNode
+ if (!innerNode)
+ throw new Error(
+ `No output node found for id [${this.id}] slot [${slot}] ${output.name}`
+ )
+
+ // Recurse into the subgraph
+ const innerNodeExecutionId = [
+ ...this.subgraphNodePath,
+ node.id,
+ innerNode.id
+ ].join(':')
+ const innerNodeDto = this.nodesByExecutionId.get(innerNodeExecutionId)
+ if (!innerNodeDto)
+ throw new Error(
+ `No inner node DTO found for id [${innerNodeExecutionId}]`
+ )
+
+ return innerNodeDto.resolveOutput(
+ innerResolved.link.origin_slot,
+ type,
+ visited
+ )
+ }
+}
diff --git a/docs/hel-892/setget-reference/1.37.11__src__scripts__app.ts b/docs/hel-892/setget-reference/1.37.11__src__scripts__app.ts
new file mode 100644
index 00000000..edcc6451
--- /dev/null
+++ b/docs/hel-892/setget-reference/1.37.11__src__scripts__app.ts
@@ -0,0 +1,1744 @@
+import { useEventListener, useResizeObserver } from '@vueuse/core'
+import _ from 'es-toolkit/compat'
+import type { ToastMessageOptions } from 'primevue/toast'
+import { reactive, unref } from 'vue'
+import { shallowRef } from 'vue'
+
+import { useCanvasPositionConversion } from '@/composables/element/useCanvasPositionConversion'
+import { registerProxyWidgets } from '@/core/graph/subgraph/proxyWidget'
+import { st, t } from '@/i18n'
+import type { IContextMenuValue } from '@/lib/litegraph/src/interfaces'
+import {
+ LGraph,
+ LGraphCanvas,
+ LGraphNode,
+ LiteGraph
+} from '@/lib/litegraph/src/litegraph'
+import type { Vector2 } from '@/lib/litegraph/src/litegraph'
+import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets'
+import { isCloud } from '@/platform/distribution/types'
+import { useSettingStore } from '@/platform/settings/settingStore'
+import { useTelemetry } from '@/platform/telemetry'
+import type { WorkflowOpenSource } from '@/platform/telemetry/types'
+import { useToastStore } from '@/platform/updates/common/toastStore'
+import { useWorkflowService } from '@/platform/workflow/core/services/workflowService'
+import { ComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore'
+import { useWorkflowValidation } from '@/platform/workflow/validation/composables/useWorkflowValidation'
+import {
+ type ComfyApiWorkflow,
+ type ComfyWorkflowJSON,
+ type ModelFile,
+ type NodeId,
+ isSubgraphDefinition
+} from '@/platform/workflow/validation/schemas/workflowSchema'
+import type {
+ ExecutionErrorWsMessage,
+ NodeError,
+ NodeExecutionOutput,
+ ResultItem
+} from '@/schemas/apiSchema'
+import {
+ type ComfyNodeDef as ComfyNodeDefV1,
+ isComboInputSpecV1,
+ isComboInputSpecV2
+} from '@/schemas/nodeDefSchema'
+import {
+ type BaseDOMWidget,
+ ComponentWidgetImpl,
+ DOMWidgetImpl
+} from '@/scripts/domWidget'
+import { useDialogService } from '@/services/dialogService'
+import { useSubscription } from '@/platform/cloud/subscription/composables/useSubscription'
+import { useExtensionService } from '@/services/extensionService'
+import { useLitegraphService } from '@/services/litegraphService'
+import { useSubgraphService } from '@/services/subgraphService'
+import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore'
+import { useCommandStore } from '@/stores/commandStore'
+import { useDomWidgetStore } from '@/stores/domWidgetStore'
+import { useExecutionStore } from '@/stores/executionStore'
+import { useExtensionStore } from '@/stores/extensionStore'
+import { useFirebaseAuthStore } from '@/stores/firebaseAuthStore'
+import { useNodeOutputStore } from '@/stores/imagePreviewStore'
+import { KeyComboImpl, useKeybindingStore } from '@/stores/keybindingStore'
+import { useModelStore } from '@/stores/modelStore'
+import { SYSTEM_NODE_DEFS, useNodeDefStore } from '@/stores/nodeDefStore'
+import { useSubgraphStore } from '@/stores/subgraphStore'
+import { useWidgetStore } from '@/stores/widgetStore'
+import { useWorkspaceStore } from '@/stores/workspaceStore'
+import type { ComfyExtension, MissingNodeType } from '@/types/comfy'
+import { type ExtensionManager } from '@/types/extensionTypes'
+import type { NodeExecutionId } from '@/types/nodeIdentification'
+import { graphToPrompt } from '@/utils/executionUtil'
+import { anyItemOverlapsRect } from '@/utils/mathUtil'
+import { collectAllNodes, forEachNode } from '@/utils/graphTraversalUtil'
+import {
+ getNodeByExecutionId,
+ triggerCallbackOnAllNodes
+} from '@/utils/graphTraversalUtil'
+import {
+ executeWidgetsCallback,
+ fixLinkInputSlots,
+ isImageNode
+} from '@/utils/litegraphUtil'
+import {
+ findLegacyRerouteNodes,
+ noNativeReroutes
+} from '@/utils/migration/migrateReroute'
+import { getSelectedModelsMetadata } from '@/workbench/utils/modelMetadataUtil'
+import { deserialiseAndCreate } from '@/utils/vintageClipboard'
+
+import { type ComfyApi, PromptExecutionError, api } from './api'
+import { defaultGraph } from './defaultGraph'
+import { importA1111 } from './pnginfo'
+import { $el, ComfyUI } from './ui'
+import { ComfyAppMenu } from './ui/menu/index'
+import { clone } from './utils'
+import { type ComfyWidgetConstructor } from './widgets'
+import { ensureCorrectLayoutScale } from '@/renderer/extensions/vueNodes/layout/ensureCorrectLayoutScale'
+import { extractFileFromDragEvent } from '@/utils/eventUtils'
+import { getWorkflowDataFromFile } from '@/scripts/metadata/parser'
+import { pasteImageNode } from '@/composables/usePaste'
+
+export const ANIM_PREVIEW_WIDGET = '$$comfy_animation_preview'
+
+function sanitizeNodeName(string: string) {
+ let entityMap = {
+ '&': '',
+ '<': '',
+ '>': '',
+ '"': '',
+ "'": '',
+ '`': '',
+ '=': ''
+ }
+ return String(string).replace(/[&<>"'`=]/g, function fromEntityMap(s) {
+ return entityMap[s as keyof typeof entityMap]
+ })
+}
+
+type Clipspace = {
+ widgets?: Pick[] | null
+ imgs?: HTMLImageElement[] | null
+ original_imgs?: HTMLImageElement[] | null
+ images?: any[] | null
+ selectedIndex: number
+ img_paste_mode: string
+ paintedIndex: number
+ combinedIndex: number
+}
+
+export class ComfyApp {
+ /**
+ * List of entries to queue
+ */
+ private queueItems: {
+ number: number
+ batchCount: number
+ queueNodeIds?: NodeExecutionId[]
+ }[] = []
+ /**
+ * If the queue is currently being processed
+ */
+ private processingQueue: boolean = false
+
+ /**
+ * Content Clipboard
+ * @type {serialized node object}
+ */
+ static clipspace: Clipspace | null = null
+ static clipspace_invalidate_handler: (() => void) | null = null
+ static open_maskeditor: (() => void) | null = null
+ static maskeditor_is_opended: (() => void) | null = null
+ static clipspace_return_node = null
+
+ vueAppReady: boolean
+ api: ComfyApi
+ ui: ComfyUI
+ extensionManager!: ExtensionManager
+ private _nodeOutputs!: Record
+ nodePreviewImages: Record
+
+ private rootGraphInternal: LGraph | undefined
+
+ // TODO: Migrate internal usage to the
+ /** @deprecated Use {@link rootGraph} instead */
+ get graph(): unknown {
+ return this.rootGraphInternal!
+ }
+
+ get rootGraph(): LGraph {
+ if (!this.rootGraphInternal) {
+ console.error('ComfyApp graph accessed before initialization')
+ }
+ return this.rootGraphInternal!
+ }
+
+ canvas!: LGraphCanvas
+ dragOverNode: LGraphNode | null = null
+ readonly canvasElRef = shallowRef()
+ get canvasEl() {
+ // TODO: Fix possibly undefined reference
+ return unref(this.canvasElRef)!
+ }
+
+ private configuringGraphLevel: number = 0
+ get configuringGraph() {
+ return this.configuringGraphLevel > 0
+ }
+ ctx!: CanvasRenderingContext2D
+ bodyTop: HTMLElement
+ bodyLeft: HTMLElement
+ bodyRight: HTMLElement
+ bodyBottom: HTMLElement
+ canvasContainer: HTMLElement
+ menu: ComfyAppMenu
+ // Set by Comfy.Clipspace extension
+ openClipspace: () => void = () => {}
+
+ private positionConversion?: {
+ clientPosToCanvasPos: (pos: Vector2) => Vector2
+ canvasPosToClientPos: (pos: Vector2) => Vector2
+ }
+
+ /**
+ * The node errors from the previous execution.
+ * @deprecated Use useExecutionStore().lastNodeErrors instead
+ */
+ get lastNodeErrors(): Record | null {
+ return useExecutionStore().lastNodeErrors
+ }
+
+ /**
+ * The error from the previous execution.
+ * @deprecated Use useExecutionStore().lastExecutionError instead
+ */
+ get lastExecutionError(): ExecutionErrorWsMessage | null {
+ return useExecutionStore().lastExecutionError
+ }
+
+ /**
+ * @deprecated Use useExecutionStore().executingNodeId instead
+ * TODO: Update to support multiple executing nodes. This getter returns only the first executing node.
+ * Consider updating consumers to handle multiple nodes or use executingNodeIds array.
+ */
+ get runningNodeId(): NodeId | null {
+ return useExecutionStore().executingNodeId
+ }
+
+ /**
+ * @deprecated Use useWorkspaceStore().shiftDown instead
+ */
+ get shiftDown(): boolean {
+ return useWorkspaceStore().shiftDown
+ }
+
+ /**
+ * @deprecated Use useWidgetStore().widgets instead
+ */
+ get widgets(): Record {
+ return Object.fromEntries(useWidgetStore().widgets.entries())
+ }
+
+ /**
+ * @deprecated storageLocation is always 'server' since
+ * https://github.com/comfyanonymous/ComfyUI/commit/53c8a99e6c00b5e20425100f6680cd9ea2652218
+ */
+ get storageLocation() {
+ return 'server'
+ }
+
+ /**
+ * @deprecated storage migration is no longer needed.
+ */
+ get isNewUserSession() {
+ return false
+ }
+
+ /**
+ * @deprecated Use useExtensionStore().extensions instead
+ */
+ get extensions(): ComfyExtension[] {
+ return useExtensionStore().extensions
+ }
+
+ /**
+ * The progress on the current executing node, if the node reports any.
+ * @deprecated Use useExecutionStore().executingNodeProgress instead
+ */
+ get progress() {
+ return useExecutionStore()._executingNodeProgress
+ }
+
+ /**
+ * @deprecated Use {@link isImageNode} from @/utils/litegraphUtil instead
+ */
+ static isImageNode(node: LGraphNode) {
+ return isImageNode(node)
+ }
+
+ /**
+ * Resets the canvas view to the default
+ * @deprecated Use {@link useLitegraphService().resetView} instead
+ */
+ resetView() {
+ useLitegraphService().resetView()
+ }
+
+ constructor() {
+ this.vueAppReady = false
+ this.ui = new ComfyUI(this)
+ this.api = api
+ // Dummy placeholder elements before GraphCanvas is mounted.
+ this.bodyTop = $el('div.comfyui-body-top')
+ this.bodyLeft = $el('div.comfyui-body-left')
+ this.bodyRight = $el('div.comfyui-body-right')
+ this.bodyBottom = $el('div.comfyui-body-bottom')
+ this.canvasContainer = $el('div.graph-canvas-container')
+
+ this.menu = new ComfyAppMenu(this)
+
+ /**
+ * Stores the execution output data for each node
+ * @type {Record}
+ */
+ this.nodeOutputs = {}
+
+ /**
+ * Stores the preview image data for each node
+ * @type {Record}
+ */
+ this.nodePreviewImages = {}
+ }
+
+ get nodeOutputs() {
+ return this._nodeOutputs
+ }
+
+ set nodeOutputs(value) {
+ this._nodeOutputs = value
+ if (this.vueAppReady)
+ useExtensionService().invokeExtensions('onNodeOutputsUpdated', value)
+ }
+
+ /**
+ * If the user has specified a preferred format to receive preview images in,
+ * this function will return that format as a url query param.
+ * If the node's outputs are not images, this param should not be used, as it will
+ * force the server to load the output file as an image.
+ */
+ getPreviewFormatParam() {
+ let preview_format = useSettingStore().get('Comfy.PreviewFormat')
+ if (preview_format) return `&preview=${preview_format}`
+ else return ''
+ }
+
+ getRandParam() {
+ if (isCloud) return ''
+ return '&rand=' + Math.random()
+ }
+
+ static onClipspaceEditorSave() {
+ if (ComfyApp.clipspace_return_node) {
+ ComfyApp.pasteFromClipspace(ComfyApp.clipspace_return_node)
+ }
+ }
+
+ static onClipspaceEditorClosed() {
+ ComfyApp.clipspace_return_node = null
+ }
+
+ static copyToClipspace(node: LGraphNode) {
+ var widgets = null
+ if (node.widgets) {
+ widgets = node.widgets.map(({ type, name, value }) => ({
+ type,
+ name,
+ value
+ }))
+ }
+
+ var imgs = undefined
+ var orig_imgs = undefined
+ if (node.imgs != undefined) {
+ imgs = []
+ orig_imgs = []
+
+ for (let i = 0; i < node.imgs.length; i++) {
+ imgs[i] = new Image()
+ imgs[i].src = node.imgs[i].src
+ orig_imgs[i] = imgs[i]
+ }
+ }
+
+ var selectedIndex = 0
+ if (node.imageIndex) {
+ selectedIndex = node.imageIndex
+ }
+
+ const paintedIndex = imgs ? imgs.length + 1 : 1
+ const combinedIndex = imgs ? imgs.length + 2 : 2
+
+ // for vueNodes mode
+ const images =
+ node.images ?? useNodeOutputStore().getNodeOutputs(node)?.images
+
+ ComfyApp.clipspace = {
+ widgets: widgets,
+ imgs: imgs,
+ original_imgs: orig_imgs,
+ images: images,
+ selectedIndex: selectedIndex,
+ img_paste_mode: 'selected', // reset to default im_paste_mode state on copy action
+ paintedIndex: paintedIndex,
+ combinedIndex: combinedIndex
+ }
+
+ ComfyApp.clipspace_return_node = null
+
+ if (ComfyApp.clipspace_invalidate_handler) {
+ ComfyApp.clipspace_invalidate_handler()
+ }
+ }
+
+ static pasteFromClipspace(node: LGraphNode) {
+ if (ComfyApp.clipspace) {
+ // image paste
+ let combinedImgSrc: string | undefined
+ if (
+ ComfyApp.clipspace.combinedIndex !== undefined &&
+ ComfyApp.clipspace.imgs &&
+ ComfyApp.clipspace.combinedIndex < ComfyApp.clipspace.imgs.length
+ ) {
+ combinedImgSrc =
+ ComfyApp.clipspace.imgs[ComfyApp.clipspace.combinedIndex].src
+ }
+ if (ComfyApp.clipspace.imgs && node.imgs) {
+ // Update node.images even if it's initially undefined (vueNodes mode)
+ if (ComfyApp.clipspace.images) {
+ if (ComfyApp.clipspace['img_paste_mode'] == 'selected') {
+ node.images = [
+ ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']]
+ ]
+ } else {
+ node.images = ComfyApp.clipspace.images
+ }
+
+ if (app.nodeOutputs[node.id + ''])
+ app.nodeOutputs[node.id + ''].images = node.images
+ }
+
+ if (ComfyApp.clipspace.imgs) {
+ // deep-copy to cut link with clipspace
+ if (ComfyApp.clipspace['img_paste_mode'] == 'selected') {
+ const img = new Image()
+ img.src =
+ ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src
+ node.imgs = [img]
+ node.imageIndex = 0
+ } else {
+ const imgs = []
+ for (let i = 0; i < ComfyApp.clipspace.imgs.length; i++) {
+ imgs[i] = new Image()
+ imgs[i].src = ComfyApp.clipspace.imgs[i].src
+ node.imgs = imgs
+ }
+ }
+ }
+ }
+
+ // Paste the RGB canvas if paintedindex exists
+ if (
+ ComfyApp.clipspace.imgs?.[ComfyApp.clipspace.paintedIndex] &&
+ node.imgs
+ ) {
+ const paintedImg = new Image()
+ paintedImg.src =
+ ComfyApp.clipspace.imgs[ComfyApp.clipspace.paintedIndex].src
+ node.imgs.push(paintedImg) // Add the RGB canvas to the node's images
+ }
+
+ // Store only combined image inside the node if it exists
+ if (
+ ComfyApp.clipspace.imgs?.[ComfyApp.clipspace.combinedIndex] &&
+ node.imgs &&
+ combinedImgSrc
+ ) {
+ const combinedImg = new Image()
+ combinedImg.src = combinedImgSrc
+ node.imgs = [combinedImg]
+ }
+
+ if (node.widgets) {
+ if (ComfyApp.clipspace.images) {
+ const clip_image =
+ ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']]
+ const index = node.widgets.findIndex((obj) => obj.name === 'image')
+ if (index >= 0) {
+ if (
+ node.widgets[index].type != 'image' &&
+ typeof node.widgets[index].value == 'string' &&
+ clip_image.filename
+ ) {
+ node.widgets[index].value =
+ (clip_image.subfolder ? clip_image.subfolder + '/' : '') +
+ clip_image.filename +
+ (clip_image.type ? ` [${clip_image.type}]` : '')
+ } else {
+ node.widgets[index].value = clip_image
+ }
+ }
+ }
+ if (ComfyApp.clipspace.widgets && node.widgets) {
+ ComfyApp.clipspace.widgets.forEach(({ type, name, value }) => {
+ const prop = node.widgets?.find(
+ (obj) => obj.type === type && obj.name === name
+ )
+ if (prop && prop.type != 'button') {
+ const valueObj = value as Record | undefined
+ if (
+ prop.type != 'image' &&
+ typeof prop.value == 'string' &&
+ valueObj?.filename
+ ) {
+ const resultItem = value as ResultItem
+ prop.value =
+ (resultItem.subfolder ? resultItem.subfolder + '/' : '') +
+ resultItem.filename +
+ (resultItem.type ? ` [${resultItem.type}]` : '')
+ } else {
+ prop.value = value
+ prop.callback?.(value)
+ }
+ }
+ })
+ }
+ }
+
+ app.canvas.setDirty(true)
+
+ useNodeOutputStore().updateNodeImages(node)
+ }
+ }
+
+ /**
+ * Adds a handler allowing drag+drop of files onto the window to load workflows
+ */
+ private addDropHandler() {
+ // Get prompt from dropped PNG or json
+ useEventListener(document, 'drop', async (event: DragEvent) => {
+ try {
+ event.preventDefault()
+ event.stopPropagation()
+
+ const n = this.dragOverNode
+ this.dragOverNode = null
+ // Node handles file drop, we dont use the built in onDropFile handler as its buggy
+ // If you drag multiple files it will call it multiple times with the same file
+ if (await n?.onDragDrop?.(event)) return
+
+ const fileMaybe = await extractFileFromDragEvent(event)
+ if (!fileMaybe) return
+
+ const workspace = useWorkspaceStore()
+ try {
+ workspace.spinner = true
+ await this.handleFile(fileMaybe, 'file_drop')
+ } finally {
+ workspace.spinner = false
+ }
+ } catch (error: unknown) {
+ useToastStore().addAlert(t('toastMessages.dropFileError', { error }))
+ }
+ })
+
+ // Always clear over node on drag leave
+ useEventListener(this.canvasElRef, 'dragleave', async () => {
+ if (!this.dragOverNode) return
+ this.dragOverNode = null
+ this.canvas.setDirty(false, true)
+ })
+
+ // Add handler for dropping onto a specific node
+ useEventListener(
+ this.canvasElRef,
+ 'dragover',
+ (event: DragEvent) => {
+ this.canvas.adjustMouseEvent(event)
+ const node = this.canvas.graph?.getNodeOnPos(
+ event.canvasX,
+ event.canvasY
+ )
+
+ if (!node?.onDragOver?.(event)) {
+ this.dragOverNode = null
+ return
+ }
+
+ this.dragOverNode = node
+
+ // dragover event is fired very frequently, run this on an animation frame
+ requestAnimationFrame(() => {
+ this.canvas.setDirty(false, true)
+ })
+ },
+ false
+ )
+ }
+
+ /**
+ * Handle keypress
+ */
+ private addProcessKeyHandler() {
+ const origProcessKey = LGraphCanvas.prototype.processKey
+ LGraphCanvas.prototype.processKey = function (e: KeyboardEvent) {
+ if (!this.graph) return
+
+ if (e.target instanceof Element && e.target.localName == 'input') {
+ return
+ }
+
+ if (e.type == 'keydown' && !e.repeat) {
+ const keyCombo = KeyComboImpl.fromEvent(e)
+ const keybindingStore = useKeybindingStore()
+ const keybinding = keybindingStore.getKeybinding(keyCombo)
+
+ if (
+ keybinding &&
+ keybinding.targetElementId === 'graph-canvas-container'
+ ) {
+ useCommandStore().execute(keybinding.commandId)
+
+ this.graph.change()
+ e.preventDefault()
+ e.stopImmediatePropagation()
+ return
+ }
+
+ // Ctrl+C Copy
+ if (e.key === 'c' && (e.metaKey || e.ctrlKey)) {
+ return
+ }
+
+ // Ctrl+V Paste
+ if (
+ (e.key === 'v' || e.key == 'V') &&
+ (e.metaKey || e.ctrlKey) &&
+ !e.shiftKey
+ ) {
+ return
+ }
+ }
+
+ // Fall through to Litegraph defaults
+ return origProcessKey.apply(this, [e])
+ }
+ }
+
+ /**
+ * Handles updates from the API socket
+ */
+ private addApiUpdateHandlers() {
+ api.addEventListener('status', ({ detail }) => {
+ this.ui.setStatus(detail)
+ })
+
+ api.addEventListener('progress', () => {
+ this.canvas.setDirty(true, false)
+ })
+
+ api.addEventListener('executing', () => {
+ this.canvas.setDirty(true, false)
+ })
+
+ api.addEventListener('executed', ({ detail }) => {
+ const nodeOutputStore = useNodeOutputStore()
+ const executionId = String(detail.display_node || detail.node)
+
+ nodeOutputStore.setNodeOutputsByExecutionId(executionId, detail.output, {
+ merge: detail.merge
+ })
+
+ const node = getNodeByExecutionId(this.rootGraph, executionId)
+ if (node && node.onExecuted) {
+ node.onExecuted(detail.output)
+ }
+ })
+
+ api.addEventListener('execution_start', () => {
+ triggerCallbackOnAllNodes(this.rootGraph, 'onExecutionStart')
+ })
+
+ api.addEventListener('execution_error', ({ detail }) => {
+ // Check if this is an auth-related error or credits-related error
+ if (
+ detail.exception_message?.includes(
+ 'Unauthorized: Please login first to use this node.'
+ )
+ ) {
+ useDialogService().showApiNodesSignInDialog([detail.node_type])
+ } else if (
+ detail.exception_message?.includes(
+ 'Payment Required: Please add credits to your account to use this node.'
+ )
+ ) {
+ const { isActiveSubscription } = useSubscription()
+ if (isActiveSubscription.value) {
+ useDialogService().showTopUpCreditsDialog({
+ isInsufficientCredits: true
+ })
+ }
+ } else {
+ useDialogService().showExecutionErrorDialog(detail)
+ }
+ this.canvas.draw(true, true)
+ })
+
+ api.addEventListener('b_preview_with_metadata', ({ detail }) => {
+ // Enhanced preview with explicit node context
+ const { blob, displayNodeId } = detail
+ const { setNodePreviewsByExecutionId, revokePreviewsByExecutionId } =
+ useNodeOutputStore()
+ // Ensure clean up if `executing` event is missed.
+ revokePreviewsByExecutionId(displayNodeId)
+ const blobUrl = URL.createObjectURL(blob)
+ // Preview cleanup is handled in progress_state event to support multiple concurrent previews
+ const nodeParents = displayNodeId.split(':')
+ for (let i = 1; i <= nodeParents.length; i++) {
+ setNodePreviewsByExecutionId(nodeParents.slice(0, i).join(':'), [
+ blobUrl
+ ])
+ }
+ })
+
+ api.init()
+ }
+
+ /** Flag that the graph is configuring to prevent nodes from running checks while its still loading */
+ private addConfigureHandler() {
+ const app = this
+ const configure = LGraph.prototype.configure
+ LGraph.prototype.configure = function (...args) {
+ app.configuringGraphLevel++
+ try {
+ return configure.apply(this, args)
+ } finally {
+ app.configuringGraphLevel--
+ }
+ }
+ }
+
+ private addAfterConfigureHandler(graph: LGraph) {
+ const { onConfigure } = graph
+ graph.onConfigure = function (...args) {
+ fixLinkInputSlots(this)
+
+ // Fire callbacks before the onConfigure, this is used by widget inputs to setup the config
+ triggerCallbackOnAllNodes(this, 'onGraphConfigured')
+
+ const r = onConfigure?.apply(this, args)
+
+ // Fire after onConfigure, used by primitives to generate widget using input nodes config
+ triggerCallbackOnAllNodes(this, 'onAfterGraphConfigured')
+
+ return r
+ }
+ }
+
+ /**
+ * Set up the app on the page
+ */
+ async setup(canvasEl: HTMLCanvasElement) {
+ this.bodyTop = document.getElementById('comfyui-body-top')!
+ this.bodyLeft = document.getElementById('comfyui-body-left')!
+ this.bodyRight = document.getElementById('comfyui-body-right')!
+ this.bodyBottom = document.getElementById('comfyui-body-bottom')!
+ this.canvasContainer = document.getElementById('graph-canvas-container')!
+
+ this.canvasElRef.value = canvasEl
+
+ await useWorkspaceStore().workflow.syncWorkflows()
+ //Doesn't need to block. Blueprints will load async
+ void useSubgraphStore().fetchSubgraphs()
+ await useExtensionService().loadExtensions()
+
+ this.addProcessKeyHandler()
+ this.addConfigureHandler()
+ this.addApiUpdateHandlers()
+
+ const graph = new LGraph()
+
+ // Register the subgraph - adds type wrapper for Litegraph's `createNode` factory
+ graph.events.addEventListener('subgraph-created', (e) => {
+ try {
+ const { subgraph, data } = e.detail
+ useSubgraphService().registerNewSubgraph(subgraph, data)
+ } catch (err) {
+ console.error('Failed to register subgraph', err)
+ useToastStore().add({
+ severity: 'error',
+ summary: 'Failed to register subgraph',
+ detail: err instanceof Error ? err.message : String(err)
+ })
+ }
+ })
+
+ this.addAfterConfigureHandler(graph)
+
+ this.rootGraphInternal = graph
+ this.canvas = new LGraphCanvas(canvasEl, graph)
+ // Make canvas states reactive so we can observe changes on them.
+ this.canvas.state = reactive(this.canvas.state)
+
+ this.ctx = canvasEl.getContext('2d')!
+
+ LiteGraph.alt_drag_do_clone_nodes = true
+ LiteGraph.macGesturesRequireMac = false
+
+ this.canvas.canvas.addEventListener<'litegraph:set-graph'>(
+ 'litegraph:set-graph',
+ (e) => {
+ const { newGraph } = e.detail
+
+ const widgetStore = useDomWidgetStore()
+
+ const activeWidgets: Record<
+ string,
+ BaseDOMWidget